问题 G: Trained?
时间限制: 1 Sec 内存限制: 128 MB
提交: 111 解决: 65
[提交] [状态] [讨论版] [命题人:admin]
题目描述
Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.
The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button ai will be lighten up. It is possible that i=ai. When Button i is not lighten up, nothing will happen by pressing it.
Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.
Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.
Constraints
2≤N≤105
1≤ai≤N
输入
Input is given from Standard Input in the following format:
N
a1
a2
:
aN
输出
Print −1 if it is impossible to lighten up Button 2. Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.
样例输入
3 3 1 2
样例输出
2
提示
Press Button 1, then Button 3.
解析:因为有N个数,如果我们从起始的1开始,一个一个的按下,如果这样进行了N次,还没使得2号起来的话,说明肯定那个地方出现的循环结,这样一直在循环结中绕圈肯定出不来。
#include <iostream>
#define N 100005
using namespace std;
int a[N];
int main()
{
int n;
int ans = 0,flag = 0;
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
}
int x = 1;
ans++;
for(int i = 1; i <= n; i++){ //循环一圈后还没是2号起来,说明出现了循环;
x = a[x];
ans++;
if(x == 2){
flag = 1;
break;
}
}
if(flag){
cout << ans-1 << endl;
}
else
cout << "-1" << endl;
return 0;
}