AtCoder Beginner Contest 065(B - Trained?)

B - Trained?

大意是从第一个按钮开始,按的是几下次就从几开始按,求按的2时最小的按数是多少,没有则是0;

 1 #include <bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 const int MAX_N = 1e5+10;
 5 int a[MAX_N];
 6 int main(){
 7     int n;
 8     cin >> n;
 9     for(int i = 1; i <= n; i ++) cin>>a[i];
10     int ans = 0, flag = 0;
11     for(int i = 1; a[i] != i; i = a[i]){;
12         ans++;
13         if(a[i] == 2){
14             flag = 1;
15             break;
16         }
17         if(ans > n)break;
18     }
19     if(flag) cout<< ans << endl;
20     else cout << -1 << endl;
21     return 0;
22 }

 

posted @ 2017-06-24 22:03  starry_sky  阅读(353)  评论(0编辑  收藏  举报