Problem:


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 a_i will be lighten up. It is possible that i=a_i.
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 ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

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



Sample input:
3
3
1
2


Sample output:
2

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

## Library

import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools
import copy

## input

# n=int(input())
# A,B,C,D=map(int, input().split())
# string = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split()) 
#    P = [list(map(int,input().split())) for i in range(M)]


N = int(input())
A = [int(input()) for _ in range(N)]

if A[0] == 2:
    print(1)
    sys.exit()

tmp = A[0]-1
for i in range(N):
    if A[tmp] == 2:
        print(i+2)
        sys.exit()
    else:
        tmp = A[tmp]-1

print(-1)

Submission status: Accepted

Solution code:
from collections import defaultdict

def readInt():
  return int(input())
def readInts():
  return list(map(int, input().split()))
def readChar():
  return input()
def readChars():
  return input().split()

n = readInt()
a = [readInt() for i in range(n)]

visited= [0]*(10**5+1)
b = 1
ans = 1
while 1:
  if a[b-1]==2:
    break
  elif visited[a[b-1]]==0:
    visited[a[b-1]]=1
    ans += 1
    b = a[b-1]
  else:
    print(-1)
    exit()

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
botton = []
for i in range(N):
  a = int(input())
  botton.append(a)
now = botton[0]
if now == 2:
  print(1)
else:
  flag = 0
  for i in range(N-1):
    now = botton[now-1]
    if now == 2:
      print(i+2)
      flag += 1
      break
  if flag == 0:
    print(-1)

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest

def resolve():
    lines = sys.stdin.readlines()
    lines = list(map(lambda x: int(x.rstrip()), lines))
    n = lines[0]
    i = 1
    for c in range(1, n+1):
        i = lines[i]
        if i == 2:
            print(c)
            return
    print(-1)
    
resolve()

Submission status: Accepted

Solution code:
import sys
n = int(input())
a = [int(input()) for a in range(n)]
cnt = 1
a.insert(0,0)
if a[1] ==2:
	print(1)
	sys.exit()
sel = a[1]
for i in range(n+1):
	if a[sel] == 2:
		cnt += 1
		print(cnt)
		sys.exit()
	else:
		cnt += 1
		sel = a[sel]
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = [0]*N
for i in range(N):
    a[i] = int(input())

dp = [0]*N
light = 1
while(light != 2):
    if dp[light-1] == 1:
        print(-1)
        exit()
    else:
        dp[light-1] = 1
    
    light = a[light-1]

print(sum(dp))

Submission status: Accepted

Solution code:
N=int(input())
A=[]
for i in range(N):
  A.append(int(input())-1)
L=[]
i=0
cnt=0
while True:
  if cnt>10**6:
    print(-1)
    exit()  
  i=A[i]
  L.append(i)
  cnt+=1
  if i==1:
    print(cnt)
    exit()

Submission status: Accepted

Solution code:
import sys
N = int(input())
if N < 1 or N > 10 ** 5:
    sys.exit()

int_array = []
for I in range(N):
    int_array.append(int(input()))
if len(int_array) < 0 or len(int_array) > N:
    sys.exit()

next = int_array[0]
count = 1
for L in range(N):
    if next == 2:
        print(count)
        sys.exit()
    next = int_array[next-1]
    count += 1
print("-1")

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for n in range(N)]
B = 0

for n in range(N):
  B = A[B]-1
  if B==1:
    print(n+1)
    exit()

print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	B
# CreatedDate:  2020-06-25 14:22:53 +0900
# LastModified: 2020-06-25 14:40:12 +0900
#


import os
import sys
# import numpy as np
# import pandas as pd


def main():
    n = int(input())
    a = [0]
    for i in range(n):
        a.append(int(input()))
    cnt = 0
    flag = [0]*(n+1)
    current = 1
    tmp=0
    while flag[current] == 0:
        flag[current] = flag[tmp] + 1
        tmp = current
        current = a[current]
        if current == 2:
            print(flag[tmp])
            return
    print("-1")


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
A = [int(input()) for i in range(n)]
T = {}
k = 1
cnt = 0
while True:
    if k == 2:
        print(cnt)
        exit()
    if k not in T: T[k]=1
    else:
        print(-1)
        exit()
    k = A[k-1]
    cnt+=1

Submission status: Accepted

Solution code:
def main():
  n = int(input())
  a = [int(input()) for i in range(n)]
  check_id=1
  for i in range(1,n+1):
    check_id=a[check_id-1]
    if check_id==2:
      print(i)
      break
  if check_id!=2:
      print(-1)
main()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect_left
from heapq import heappush, heappop
import networkx as nx
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
 
N = INT()
a = [0]+[INT() for _ in range(N)]

visited = [0]*(N+1)
visited[1] = 1
now = 1
cnt = 0
while not visited[a[now]]:
    now = a[now]
    visited[now] = 1
    cnt += 1
    if now == 2:
        print(cnt)
        break
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
lis = [int(input()) for i in range(N)]
a=1
for i in range(1,N+1):
    a=lis[a-1]
    if a == 2:
        print(i)
        break
if a !=2:
    print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]

count = 1
i = 0

while count < n:
  i = a[i] - 1
  if i == 1:
    print(count)
    break
  count += 1
if count >= n:
  print(-1)

Submission status: Accepted

Solution code:
n = int(input())
A = [int(input()) for _ in range(n)]

now = 0
for i in range(n):
    now = A[now] - 1
    if now == 1:
        print(i+1)
        exit()

print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
c,s = 1,a[0]
while s != 2 and c < n:c, s = c+1, a[s-1]
print(c if c < n else -1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
c = 1
s = a[0]
while s != 2 and c < n:
    c, s = c+1, a[s-1]
if c<n:
    print(c)
else:
    print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = [0]*(n+1)
for i in range(1, n+1):
    a[i] = int(input())

ans = 0
now = 1
nex = a[1]
for i in range(n):
    ans += 1
    now = nex
    nex = a[now]
    if now == 2:
        break
if ans == n:
    ans = -1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
l = []
for i in range(N):
    l.append(int(input()))

idx = 1
stopped = set([idx])
while True:
    idx = l[idx - 1]
    if idx == 2:
        print(len(stopped))
        break
    if idx in stopped:
        print(-1)
        break
    else:
        stopped.add(idx)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]

ans = 1
count = 0
for _ in range(N):
    ans = a[ans-1]
    count += 1
    if ans == 2:
        print(count)
        break
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = [0] + [int(input()) for i in range(N)]
 
now = 1
count = 0
pushed = {1}
while now != 2:
  now = A[now]
  count += 1
  if now in pushed:
    print(-1)
    quit()
  pushed.add(now)
 
print(count)

Submission status: Accepted

Solution code:
N = int(input())
A = [0] + [int(input()) for i in range(N)]

now = 1
count = 0
pushed = {1}
while now != 2:
  now = A[now]
  count += 1
  if now in pushed:
    print(-1)
    quit()
  pushed.add(now)

print(count)

Submission status: Accepted

Solution code:
N = int(input())
A = [0] * N

for _ in range(N):
    A[_] = int(input()) - 1

cur = 0
ok = False
hist = set()

while True:
    if cur == 1:
        ok = True
        break

    if cur in hist:
        break
    else:
        hist.add(cur)
    
    cur = A[cur]

if ok:
    print(len(hist))
else:
    print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
ans = 1
p = a[0]
while True:
    if p == 2:
        print(ans)
        break
    elif (p == a[p-1]) | (ans > n):
        print(-1)
        break
    else:
        p = a[p-1]
        ans += 1

Submission status: Accepted

Solution code:
N = int(input())
a_list = [int(input()) for _ in range(N)]

count = 0
li = 1
while True:
    li = a_list[li-1]
    count += 1

    if li == 2:
        answer = count
        break

    if count == N:
        answer = -1
        break 

print(answer)

Submission status: Accepted

Solution code:
import sys
import math
def I():return int(sys.stdin.readline().replace("\n",""))
def I2():return map(int,sys.stdin.readline().replace("\n","").split())
def S():return str(sys.stdin.readline().replace("\n",""))
def L():return list(sys.stdin.readline().replace("\n",""))
def Intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def Lx(k):return list(map(lambda x:int(x)*-k,sys.stdin.readline().replace("\n","").split()))

if __name__ == "__main__":
    n = I()
    a = [I() for i in range(n)]
    b = [1] + [0]*(n-1)
    cnt = 0
    j = 0
    for i in range(n):
        b[j] = 0
        b[a[j]-1] = 1
        j = a[j]-1
        cnt += 1
        #print(j,a[j]-1,b)
        if b[1] == 1:
            print(cnt)
            exit()
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for i in range(N)]

#最初はボタン１が光っている
index = 1

#押した回数0からスタート
count = 0

while count < N:
  
  if a[index-1]==2:
    count += 1
    #print(str(2) + "!!")
    print(count)
    exit()
    
  else:
    #ボタン押す
    count += 1
    #次に光るボタンの番号
    index=a[index-1]
    #print(str(index) + "!!")

print(-1)

Submission status: Accepted

Solution code:
from sys import stdin, setrecursionlimit
from collections import deque


def main():
    input = stdin.buffer.readline
    n = int(input())
    g = [int(input()) - 1 for _ in range(n)]
    q = deque([0])
    seen = [-1] * n
    seen[0] = 0

    while q:
        u = q.popleft()
        v = g[u]
        if seen[v] == -1 or seen[v] > seen[u] + 1:
            seen[v] = seen[u] + 1
            q.append(v)

    print(seen[1])


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]

index = 0
count = 1
tf = False

while True:
  if a[index]==2:
    tf = True
    break
  else:
    index=a[index]-1
    if count == n:
      break
    else:
      count += 1
if tf:
    print(count)
else:
  print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, a: "List[int]"):

    i = 0
    for _ in range(N):

        if a[i] == 2:
            print(_+1)
            return
        i = a[i] - 1

    print(-1)
    

    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    a = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, a)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
now = 1
ans = 0
while True:
    now = a[now-1]
    ans += 1
    if (now==2):
        print(ans)
        break
    elif (now==1):
        print(-1)
        break
    elif (ans>len(a)):
        print(-1)
        break

Submission status: Accepted

Solution code:

N = int(input())
A = []
for i in range(N):
    a = int(input())
    A.append(a)
    
aaa = 0    
ans = A[0]
count = 1

for i in range(N):
    if ans == 2:
        aaa = 1
        break
    else:
        ans = A[ans-1]
        count += 1
if aaa == 1:
    print(count)
else:
    print(-1)

Submission status: Accepted

Solution code:
n=int(input())
Alist=[0]+[int(input()) for i in range(n)]
 
now=1
count=0
Hist={1}
 
while now!=2:
    now=Alist[now]
    count+=1
    if now in Hist:
        count=-1
        break
    Hist.add(now)
print(count)

Submission status: Accepted

Solution code:
n=int(input())
Alist=[0]+[int(input()) for i in range(n)]

now=1
Hist={1}

for i in range(n):
    now=Alist[now]
    if now==2:
        print(i+1)
        break
    if now in Hist:
        print(-1)
        break
    Hist.add(now)

Submission status: Accepted

Solution code:
n=int(input())
Alist=[0]+[int(input()) for i in range(n)]

now=1
count=0

for _ in range(n):
    now=Alist[now]
    count+=1
    if now==2:
        print(count)
        exit()
print(-1)

Submission status: Accepted

Solution code:
N = int(input())

L = []

for i in range (0, N):
	L.append(int(input()))

counter = 0
initial = 0

for i in range (0, 2*N+1):
	initial = L[initial]-1
	counter+=1
	if initial == 1:
		print(counter)
		exit()

print(-1)

Submission status: Accepted

Solution code:
#! env python
# -*- coding: utf-8 -*-

import os
import sys


# ac_py.main
# Date: 2020/06/14
# Filename: main 
# Author: acto_mini

def main():
    N = int(input())

    a = []
    for i in range(N):
        a.append(int(input()))

    button = 1
    for i in range(N+1):
        if button == 2:
            print(i)
            exit()
        button = a[button - 1]
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
a=[]
for i in range(n):
  a.append(int(input())-1)
i=0

out=0
kai=0
while i!=1:
  kai+=1
  out+=1
  i=a[i]
  if kai>n:
    out=-1
    break

print(out)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input())-1 for _ in range(N)]

b = [True]*N
b[0] = False
i = a[0]
cnt = 1
while b[i]:
    if i == 1:
        print(cnt)
        break
    b[i] = False
    i = a[i]
    cnt += 1
else:
    print(-1)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    a = [int(input()) for _ in range(N)]
    i = 1
    ans = 0

    for K in range(N):
        i = a[i-1]
        ans += 1
        if i == 2:
            return ans
    ans = -1
    return ans

print(main())

Submission status: Accepted

Solution code:
def resolve():
    n = int(input())
    next_button = list()

    for i in range(n):
        a = int(input())
        next_button.append(a)
    
    now_button = 1
    ans = 0
    for i in range(n):
        now_button = next_button[now_button-1]
        #print(f"{i} times now button is {now_button}")
        if now_button == 2:
            ans += 1
            break
        ans += 1

    if ans == n:
        print(-1)
    else:
        print(ans)
resolve()

Submission status: Accepted

Solution code:
N=int(input())
a=[int(input()) for i in range(N)]
ans=-1
button=1
count=0
while count<N:
  count+=1
  if a[button-1]==2:
    ans=count
    break
  else:
    button=a[button-1]
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
a=[int(input()) for i in range(N)]
ans=0
cur=0
while True:
  ans+=1
  if a[cur]==2:
    print(ans)
    exit()
  else:
    cur=a[cur]-1
    if ans>=N:
      print(-1)
      exit()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
b = 1
for j in range(n):
    b = a[b - 1]
    if b == 2:
        print(j + 1)
        break
if b != 2:
    print(-1)

Submission status: Accepted

Solution code:


N = int(input())
A = [int(input()) for i in range(N)]
 
 
cnt = 1
a = A[0]
while True:
	if a == 2:
		print(cnt)
		break
	cnt += 1

	a = A[a-1]

	if cnt > N:
		print(-1)
		break

Submission status: Accepted

Solution code:
n = int(input())

buttons = []
for i in range(n):
    num = int(input())
    buttons.append(num - 1)

counter = 0
i = 0
while buttons[i] != -1:
    if i == 1:
        print(counter)
        break
    else:
        counter += 1
        _i = i
        i = buttons[i]
        buttons[_i] = -1
else:
    print(-1)

Submission status: Accepted

Solution code:
n=int(input())
c=[int(input())for i in range(n)]
a=[0]
a.extend(c)
x=a[1]
a[1]=-1
cnt=1
for i in range(n):
    if x==2:
        print(cnt)
        exit()
    cnt+=1

    y=a[x]
    a[x]=-1
    x=y
    if x==-1:
        print(-1)
        exit()

Submission status: Accepted

Solution code:
n=int(input())
l=[]
for i in range(n):
    l.append(int(input()))
x=1 
c=0
while True:
    x=l[x-1]
    c+=1
    if x==2:
        print(c)
        break
    elif c>n:
        print(-1)
        break

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
now = a[0]
c = 1

if now == 2:
    print(1)
    exit()

for i in range(n):
    now = a[now-1]
    c += 1
    if now == 2:
        print(c)
        exit()
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
now = a[0]
c = 1

if now == 2:
    print(1)
    exit()

for i in range(n):
    now = a[now-1]
    c += 1
    if now == 2:
        print(c)
        exit()
print(-1)

Submission status: Accepted

Solution code:

def calc(N, button) : 
  count = 0
  position = 1
  next = button[1]
  flag = [False] * (10 ** 5 + 1)
  
  for i in range(1, N + 1) : 
    count += 1
    next = button[position]
    if next == 2 : 
      return count
    position = next
    if flag[position] == True : 
      return -1
    flag[position] = True
    
  return -1


N = int(input())

button = [0] * (10 ** 5 + 1)

for i in range(1, N + 1) : 
  button[i] = int(input())
  
print(calc(N, button))

Submission status: Accepted

Solution code:
n = int(input())
a = []
for _ in range(n):
    a.append(int(input()) - 1)
cnt = 0
i = 0
flag = [False] * n
while not flag[i]:
    cnt += 1
    flag[i] = True
    i = a[i]
    if i == 1:
        print(cnt)
        break
else:
    print(-1)

Submission status: Accepted

Solution code:
n = int(input())

a=[""]*n

for i in range(n):
  a[i] = int(input())

light = a[0]
counter = 1
result = -1
if light == 2:
  print(1)
  exit()
for i in range(n):
  light = a[light-1]
  counter += 1
  if light == 2:
    result = counter
    break
print(result)

Submission status: Accepted

Solution code:
N = int(input())
buttons = [0] * (N + 1)
for i in range(N):
    buttons[i + 1] = int(input())
current = 1
for i in range(N):
    current = buttons[current]
    if current == 2:
        print(i + 1)
        exit()
print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(input()) for i in range(n)]
x=1
cnt=0
y=[1]
while True:
    x=a[x-1]
    cnt+=1
    y.append(x)
    if x==2:
        print(cnt)
        break
    elif x==1:
        print('-1')
        break
    elif cnt==100000:
        print(-1)
        break
    else:
        continue

Submission status: Accepted

Solution code:
N = int(input())
A = []
for _ in range(N):
    A.append(int(input()))

pushed = [False] * N
pushed[0] = True
now = 0
cnt = 0

while True:
    next = A[now] - 1

    if pushed[next]:
        cnt = -1
        break

    if next == 1:
        cnt += 1
        break

    if next != 1:
        now = next
        pushed[next] = True
        cnt += 1


print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
T = [False for i in range(n)]
tmp = 1
T[0] = True
count = 1
while True:
    tmp = a[tmp-1]
    if T[tmp -1]:
        print(-1)
        exit()
    T[tmp-1] = True
    if tmp == 2:
        print(count)
        break
    count+=1

Submission status: Accepted

Solution code:
n = int(input())
A = []
cnt = 0
for i in range(n):
    a = int(input())
    A.append(a)
for i in range(1, n+1):
    if i == 1:
        now = A[i-1]
        cnt += 1
        if now == 2:
            print(cnt)
            exit()
    else:
        now = A[now-1]
        cnt += 1
        if now == 2:
            print(cnt)
            exit()
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
x = [int(input()) for i in range(N)]
cnt = 1
num = x[0]
if num != 2:
    cnt = 2
    for i in range(N):
        num = x[num-1]

        if(num == 2):
            break
        cnt += 1
if cnt == N + 2:
    cnt = -1
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]

count = 1
next = a[0]
flg = 0

while True:
  if next == 2:
    break
  if count == n:
    flg = 1
    break
  
  count += 1
  next = a[next-1]

if flg == 1:
  print(-1)
else:
  print(count)

Submission status: Accepted

Solution code:
n = int(input())

button = list()

for x in range(n):
    button.append(int(input())-1)

now = 0
count = 0

while True:
    if now == 1:
        print(count)
        break

    if count >= n:
        print(-1)
        break

    count += 1
    now = button[now]

Submission status: Accepted

Solution code:
n = int(input())
a = {}

for i in range(n):
  a[i + 1] = int(input())

b = a[1]
k = 1
if b == 2:
  ans = k
else:
  f = 0
  for i in range(n):
    b = a[b]
    k += 1
    if b == 2:
      ans = k
      f = 1
      break
    else:
      next
  if f == 0:
    ans = -1
print(ans)

Submission status: Accepted

Solution code:
import sys
n = int(input())
ls = [int(input()) for _ in range(n)]
if 2 not in ls:
    print(-1)
    sys.exit()
i = 1
k = 0
for j in range(n):
    i = ls[i-1]
    k += 1
    if i == 2:
        print(k)
        sys.exit()
print(-1)

Submission status: Accepted

Solution code:
n = int(input())

A = [int(input()) for i in range(n)]

A = [0] + A
count = 0
light = 1
if 2 not in A:
  print("-1")
  exit()
else:
  while light != 2 and count <= n:
    count += 1
    light = A[light] #A = [0] + Aとしているので，これでよい．light-1としなくてよい．

if count <= n:
  print(count)
else:
  print("-1")

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
b = [0]
target = 0
count = 0
while(True):
    target = a[target] - 1
    count += 1
    if count > n:
        print("-1")
        break
    if target == 1:
        print(count)
        break

Submission status: Accepted

Solution code:
def main():
    a = [int(input())-1 for _ in range(int(input()))]
    now = 0
    sumi = set()
    count = 0
    while now != 1:
        if now in sumi:
            print(-1)
            return
        sumi.add(now)
        now = a[now]
        count += 1
    print(count)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
ans = -1
x = a[0]
m = 0
for i in range(n):
    m += 1
    if x == 2:
        ans = m
        break
    else:
        x = a[x-1]
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Thu Jun  4 22:35:46 2020

@author: naoki
"""

import sys

N = int(input()) # ボタンの個数
a = [int(input()) for i in range(N)] #k番目のボタンに書いてある番号
a = [0] + a #配列の番号合わせ
count = 0 #ボタンを押す回数
light = 1 # 光っているボタンの番号
if 2 not in a: # 2と書かれたボタンがない場合は不可能なので-1を出力
    print(-1)
    sys.exit()
else: # 2と書かれたボタンがある場合
    while light != 2 and count <= N : # 光っているボタンが2になるか、ボタンを押した回数がNを超えてしまったら終了
        count += 1 
        light = a[light]#左から数えたときに光っているボタンの番号の順番にあるボタンに書かれている数字が次に光るボタンの番号である。

if count <= N:        
        print(count)
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
N = I()
a = [0]+[I() for _ in range(N)]
ans,now = 0,1
for _ in range(N):
    temp = a[now]
    ans += 1
    if temp==2:
        print(ans)
        break
    now = temp
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
N = I()
a = [0]+[I() for _ in range(N)]
ans,now = 0,1
for _ in range(N):
    temp = a[now]
    ans += 1
    if temp==2:
        print(ans)
        break
    else:
        now = temp
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = []
for i in range(N):
    a.append(int(input()))
ans = 0
light = 0
for i in range(10**6):
    light = a[light]-1
    ans += 1
    if light == 1:
        print(ans)
        exit()
print(-1)

Submission status: Accepted

Solution code:

N = int(input())
a = []
for _ in range(N):
    temp = int(input())
    a.append(temp)

index = 0
current = 0
count = 0
for i in range(N):
    if current == 2:
        print(count)
        break
    current = a[index]
    index = current - 1
    count += 1
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) - 1 for _ in range(N)]

now = 0
for i in range(1, N + 1):
    now = A[now]
    if now == 1:
        print(i)
        exit()

print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=[]
for i in range(n):
  a.append(int(input()))
i=0
count=1
frag=-1
for j in range(n):
  if a[i]==2:
    frag=count
    break
  else:
    i=a[i]-1
    count+=1
print(frag)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input())-1 for _ in range(N)]

now = 0
for i in range(N):
  now = a[now]
  if now == 1:
    print(i+1)
    break
else:
  print(-1)

Submission status: Accepted

Solution code:
import numpy as np

n = int(input())

array = np.zeros(n, dtype = np.int)

for i in range(n):
    array[i] = input()

next_number = array[0]
counter = 1

for i in range(n):
    if next_number == 2:
        print(counter)
        break
    else:
        next_number = array[next_number-1]
        counter += 1
        if i == n-1:
            print(-1)

Submission status: Accepted

Solution code:
# For taking integer inputs.
import math


def inp():
    return(int(input()))


# For taking List inputs.
def inlist():
    return(list(map(int, input().split())))


# For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable.
def instr():
    s = input()
    return(list(s[:len(s)]))


# For taking space seperated integer variable inputs.
def invr():
    return(map(int, input().split()))


n = inp()
a = [0]

for i in range(n):
    a.append(inp())

i = 1
c = 1

while a[i] != 2:
    if a[i] == -1:
        c = -1
        break
    c += 1
    temp = i
    i = a[i]
    a[temp] = -1
print(c)

Submission status: Accepted

Solution code:
N=int(input())
A=[int(input()) for i in range(N)]
B=set()
B.add(1)
b=1
count=0
while True:
    b=A[b-1]
    count+=1
    if b==2:
        print(count)
        break
    elif b in B:
        print(-1)
        break
    else:
        B.add(b)

Submission status: Accepted

Solution code:
N=int(input())
lamps=[]
for a in range(N):
    _=int(input())
    lamps.append(_)
lamps.insert(0,"aaa")

PressedButtons=[False]*int(N+1)

a=1
count=0

if lamps.count(2)==0:
    print("-1")
    exit()

while PressedButtons[a]==False :
    PressedButtons[a]=True
    count+=1
    a=lamps[a]
    if a==2:
        print(count)
        exit()
print('-1')

Submission status: Accepted

Solution code:
from collections import deque

N=int(input())
graph=[[] for _ in range(N)]
for i in range(N):
    a=int(input())-1
    graph[i].append(a)

d=[float("inf")]*N
d[0]=0
queue=deque([0])
while queue:
    x=queue.pop()
    for y in graph[x]:
        if d[y]!=float("inf"):
            break
        d[y]=d[x]+1
        queue.append(y)

if d[1]==float("inf"):
    print(-1)
else:
    print(d[1])

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
count = 0
i = 0
for _ in range(n):
    i = a[i]-1
    count += 1
    if i == 1:
        print(count)
        break
else:
    print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(input()) for _ in range(n)]
num=a[0]
for i in range(n):
    if num==2:
        break
    num=a[num-1]
if i==n-1:
    print(-1)
else:
    print(i+1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]

count = 1
now = 0

for i in range(n):
  if a[now] == 2:
    break
  else:
    now = a[now]-1
    count += 1
#    print("now:",a[now])

if a[now] == 2:
  print(count)
else:
  print(-1)

Submission status: Accepted

Solution code:
import sys
n=int(input())
List=[int(input()) for i in range(n)]
ans=0
nxt=1
while(1):
    if ans>=n:
        print(-1)
        sys.exit()
    elif nxt==2:
        break
    nxt=List[nxt-1]
    ans+=1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
a = []
exp = {1}
for i in range(N):
  a.append(int(input()))
r = a[0]
flag = 0
ans = 0
while True:
  if(r in exp):
    flag = -1
    break
  if(r == 2):
    flag = 1
    break
  exp.add(r)
  r = a[r- 1]
  ans+= 1
  
if(flag == -1):
  print("-1")
else:
  print(ans+ 1)

Submission status: Accepted

Solution code:
class UnionFindTree:
    def __init__(self, n):
        self.__parents = [-1] * n

    def find(self, x):
        p = self.__parents[x]
        if p < 0:
            return x
        p = self.find(p)
        self.__parents[x] = p
        return p

    def union(self, x, y):
        p = self.__parents
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if p[x] > p[y]:
            x, y = y, x
        p[x] += p[y]
        p[y] = x
        return True

    def same(self, x, y):
        return self.find(x) == self.find(y)


N = int(input())
uft = UnionFindTree(N)
cur = 0
buttons = list(map(lambda x: int(x) - 1, (input() for _ in range(N))))
count = 0
while True:
    n = buttons[cur]
    count += 1
    if not uft.union(cur, n):
        count = -1
        break
    if n == 1:
        break
    cur = n
print(count)

Submission status: Accepted

Solution code:
N = int(input())
lamps = [0] * N
next_ = 0
count = 0
buttons = list(map(lambda x: int(x) - 1, (input() for _ in range(N))))
while True:
    count += 1
    lamps[next_] = 1
    next_ = buttons[next_]
    if next_ == 1:
        break
    if lamps[next_]:
        count = -1
        break

print(count)