B - Trained?
Time limit : 2sec / Memory limit : 256MB
Score : 200 points
Problem Statement
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
Input is given from Standard Input in the following format:
N a1 a2 : aN
Output
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.
Sample Input 1
3 3 1 2
Sample Output 1
2
Press Button 1, then Button 3.
Sample Input 2
4 3 4 1 2
Sample Output 2
-1
Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.
Sample Input 3
5 3 3 4 2 4
Sample Output 3
3
#include <iostream>
using namespace std;
int main()
{
int n;
int a[100000+100];
int b[100000+100];
while(cin>>n){
memset(b,-1,sizeof(b));
for(int i=1;i<=n;i++){
cin>>a[i]; b[i]=0;
}
int flag=0; int k=0;
int i=1;
while(1){
if(b[i]==0){
b[i]=1; k++;
i=a[i];
if(i==2){
flag=1; break;
}
}
else if(b[i]==1){
flag=0; break;
}
}
if(flag==0)
cout<<-1<<endl;
else
cout<<k<<endl;
}
return 0;
}