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:
import sys

input = sys.stdin.readline


def main():
    N = int(input())
    a = [0] * N
    for i in range(N):
        a[i] = int(input()) - 1

    visited = [False] * N
    visited[0] = True
    i = 0
    ans = 0
    while True:
        i = a[i]
        if visited[i]:
            ans = -1
            break
        visited[i] = True
        ans += 1
        if i == 1:
            break

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#import numpy as np
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as comb_with
#from itertools import permutations as perm


N = int(input())
#H1,M1,H2,M2,K= map(int,input().split())
#A = list(map(int,input().split()))
#B = list(map(int,input().split()))
#S= str(input())
l=[]
for i in range(N):
    B = int(input())
    l.append(B)

now=0
next=1
c=0
while c<10**6:
    now=next
    if now==2:
        print(c)
        exit()
    next=l[now-1]
    c+=1

print(-1)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    n = int(input())
    dict={}
    for i in range(n):
        dict[i] = int(input())

    dict2={}
    count = 0
    now =1
    for i in range(n):
        if now in dict2:
            print(-1)
            break
        else:
            if dict[now-1] ==2:
                count+=1
                print(count)
                break
            else:
                dict2[now]=0
                count+=1
                now = dict[now-1]

Submission status: Accepted

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

    ans = 0
    nxt = 1
    while True:
        if ans > N:
            print(-1)
            exit()
        elif nxt == 2:
            break
        nxt = a[nxt-1]
        ans += 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def li():
    return list(map(int, input().split()))
def mi():
    return map(int, input().split())
def ii():
    return int(input())
def lim(N):
    return [int(input()) for i in range(N)]

N = ii()
a = lim(N)

current = 1
result = 1

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

Submission status: Accepted

Solution code:
import sys

N = int(sys.stdin.readline())

button = sys.stdin.readlines()
button = [int(j.replace('\n','')) for j in button]


b = button[0]
counter = 0
for i in range(len(button)):
    if b == 2:
        print(counter+1)
        exit()
    else:
        b = button[b-1]
        counter = counter+1

print(-1)

Submission status: Accepted

Solution code:
_, *A = map(lambda x: int(x) - 1, open(0).read().split())
A = list(A)
pos = 0
cnt = 1
for i in range(10 ** 5 + 1):
    pos = A[pos]
    if pos == 1:
        print(cnt)
        break
    cnt += 1
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys

N = int(input())
a = [0] + [int(input()) for _ in range(N)]

current = 1
count = 0
while True:
    current = a[current]
    count += 1
    if current == 2:
        print(count)
        sys.exit(0)

    if count > 20 ** 5:
        break
print(-1)

Submission status: Accepted

Solution code:
n=int(input())

a=[int(input())-1 for i in range(n)]
c=[-1 for i in range(n)]
cu=0
c[cu]=0
for i in range(n):
  cu=a[cu]
  if c[cu]>0:
    break
  c[cu]=i+1
  
print(c[1])

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
a = 1
A = list(int(input()) for i in range(N))

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

Submission status: Accepted

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

cnt = 1
x = A[0]
while x != 2 and cnt != n:
    x = A[x - 1]
    cnt += 1
    
if cnt == n:
    print(-1)
else:
    print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
A = [int(input()) for i in range(n)]
B = []
for i, a in enumerate(A):
    B.append([i + 1, a])
    
idx = 1
for i in range(n):
    x = B[idx - 1][1]
    if x == 2:
        print(i + 1)
        break
    else:
        idx = x
else:
    print(-1)

Submission status: Accepted

Solution code:
n=int(input())
A=[int(input()) for _ in range(n)]
visit=set()
ans=-1
cnt=0
tmp=A[0]
while tmp not in visit:
  cnt+=1
  if tmp==2:
    ans=cnt
    break
  visit.add(tmp)
  tmp=A[tmp-1]
print(ans)

Submission status: Accepted

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

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

print(-1)

Submission status: Accepted

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

i = 0
cnt = 1
while True:
    if cnt > len(a):
        cnt = -1
        break
    if a[i] == 1:
        cnt = -1
        break
    elif a[i] == 2:
        break
    else:
        i = a[i] - 1
        cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())

next_li = []

for i in range(N):
    next_li.append(int(input()))

#判定処理
st = 0
c = 1
for i in range(N):
    if next_li[st] == 2:
        print(c)
        exit()
    else:
        c += 1
        st = next_li[st]-1
print(-1)

Submission status: Accepted

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

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

Submission status: Accepted

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

c = 0
d = 0
while True:
	if chk[c]:
		print (-1)
		exit()
	else:
		chk[c] = True
		if c == 1:
			print (d)
			exit()
	c = a[c]-1
	d += 1

Submission status: Accepted

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


visited = set()
cnt = 0 # 移動回数を記録する
i = 1 # 今点灯中のボタン番号、初期値は1
v = a[i] # 次に点灯するボタン番号 
f = True
while True:
    if i in visited:
        f = False
        break
    if v == 2:
        cnt += 1
        break
    visited.add(i)
    i = v
    v = a[v]
    cnt += 1

if f:
    print(cnt)
else:
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

d = [999999 for i in range(N+1)]
d[1]=0
seen = [0 for i in range(N+1)]

q = [1]
seen[1]=1

while q:
  v = q[0]
  del q[0]

  if seen[graph[v]]==0:
    q.append(graph[v])
    seen[graph[v]]=1
  if d[v]+1<d[graph[v]]:
    d[graph[v]]=d[v]+1
print(-1 if d[2]==999999 else d[2] )

Submission status: Accepted

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

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

print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = list(int(input()) for i in range(N))
now=0
ok=False
while(True):
    if A[now]==-1:
        break
    else:
        temp=now
        now=A[now]-1
        A[temp]=-1
    if now==1:
        ok=True
        break
print(A.count(-1) if ok else -1)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
pos = 1
cnt = 0
passed = [0]*(n+1)
TF = True
while TF:
  pos -= 1
  temp = a[pos]
  if passed[temp] == 1:
    TF = False
    print(-1)
  elif temp == 2:
    print(cnt+1)
    TF = False
  else:
    passed[temp] = 1
    pos = temp
    cnt += 1

Submission status: Accepted

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

i = 0
l = 1
while 1:
  i+=1
  l=a[l-1]
  if l==2:
    ans=i
    break
  if i>N:
    ans=-1
    break
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

count = 0
idx = 0
for _ in range(N):
    if A[idx] == 2:
        print(count + 1)
        exit()
    idx = A[idx] - 1
    count += 1
print(-1)

Submission status: Accepted

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

i = 1
count = 0
find = False
for _ in range(N):
    count += 1
    i = A[i-1]
    if i == 2:
        find = True
        break

if find:
    print(count)
else:
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

cur = 0
cnt = 0
for i in range(n):
    cnt += 1
    if a[cur] == 2:
        print(cnt)
        exit()
    cur = a[cur]-1
    
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = []

for i in range(n):
    a.append(int(input())-1)

button = 0
cnt = 0
done = [False] * n

while True:
    if done[button] == False:
        done[button] = True
        cnt += 1
        if a[button] == 1:
            break
        button = a[button]
    else:
        cnt = -1
        break

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
i = 0
now = 0
while(i < n):
    if now == 1:
        print(i)
        exit()
    now = a[now]-1
    i += 1
else:
    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())
buttons = [0]
target_index = 0
for _ in range(n):
    buttons.append(int(input()))

count = 0
prev_index = 1
while count < n:
    if prev_index < 1 or len(buttons) <= prev_index:
        count = -1
        break

    next_index = buttons[prev_index]
    count += 1
    if next_index == 2:
        break
    else:
        prev_index = next_index

print(count if count < n else -1)

Submission status: Accepted

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

route = set()
route.add(0)
before = 0
ans = 0
for i in range(N):
    now = a[before] - 1
    ans += 1
    if now == 1:
        break
    elif now not in route:
        route.add(now)
        before = now
    else:
        ans = -1
        break
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=[]
for _ in range(N):
  A.append(int(input())-1)
visited=[0]*N
i,ans= 0,0
while i != 1:
  if visited[i] == 0:
    visited[i] = 1
    i = A[i] # next position
    ans += 1
  else:
    ans = -1
    break
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
x = [int(input()) for i in range(n)]
ans=1
visited=[False]*n
now=0
visited[now]=True

while(1):
  #nextは次のボタンの番号
  now=x[now]-1
  if visited[now]:
    print(-1)
    break
   
  visited[now]=True
  if now==1:
    print(ans)

    break
  else:
    ans+=1

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    A = [0] + [int(input()) for _ in [0] * n]
    visited = [0] * (n+1)
    now = 1
    visited[now] = 1
    cnt = 0
    while True:
        next = A[now]
        cnt += 1
        if visited[next]:
            print(-1)
            break

        if next == 2:
            print(cnt)
            break

        visited[next] = 1
        now = next


if __name__ == "__main__":
    main()

Submission status: Accepted

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

button = 1
cnt = 0
for i in range(N):
    if button == 2:
        print(cnt)
        break
    else:
        button = A[button]
        cnt += 1
else:
    print(-1)

Submission status: Accepted

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

li = [False]*n

li[0]=1
now = 1
for i in range(n):
    now = ai[now-1] 
    if now ==2:
        print(i+1)
        exit()
    elif li[now-1] !=False:
        print(-1)
        exit()
else:
    print(-1)

Submission status: Accepted

Solution code:
def main():
    N, *A = map(int, open(0).read().split())
    count = 0
    cur = 1
    while count < N:
        count += 1
        cur = A[cur - 1]
        if cur == 2:
            print(count)
            return
    print(-1)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

u = [False for _ in range(n)]
i = 0
ans = 0
while(i != 1):
  u[i] = True
  i = a[i]
  if u[i]:
    print(-1)
    exit()
  ans += 1
print(ans)

Submission status: Accepted

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

ans,i = 0,0
check = [0]*N

while i != 1:
  check[i] += 1
  if check[i] > 1:
    ans = -1
    break
  ans += 1
  i = a[i]

print(ans)

Submission status: Accepted

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    L = [ii()-1 for _ in range(n)]
    cnt = 0
    current = 0
    while cnt < n:
        if current == 1:
            break
        current = L[current]
        cnt += 1
    
    if cnt == n:
        print(-1)
    else:
        print(cnt)



if __name__ == "__main__":
    main()

Submission status: Accepted

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

visited = [0] * n

index = 0
num_push = 0
goal = False
while True:
    if visited[index] == 1:
        break

    visited[index] = 1
    if index == 1:
        goal = True
        break

    index = as_[index]
    num_push += 1

if goal:
    print(num_push)
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
if 2 not in A:
    print(-1)
    exit()
now = 1
count = 0
past = []
while True:
    if now == 2:
        print(count)
        exit()
    if count >= N:
        print(-1)
        exit()
    count += 1
    now = A[now - 1]

Submission status: Accepted

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

idx = 0
count = 0
while True:
    if not is_visited[idx]:
        is_visited[idx] = True
    else:
        print(-1)
        break
    idx = A[idx] - 1
    count += 1
    if idx == 1:
        print(count)
        break

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

def main():
    input = sys.stdin.readline
    N = int(input())
    btn = [int(input())-1 for _ in range(N)]
    i = 0
    li = [False]*N
    #print(btn)
    
    for _ in range(N):
        li[i] = True
        k = btn[i]
        
        #print(k, li)
        if li[k]:
            print('-1')
            break
        elif k == 1:
            print(sum(li))
            break
        
        i = k
    
if __name__ == '__main__':
    main()

Submission status: Accepted

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

while True:
    light = a[light - 1]
    count += 1

    if light == 2:
        print(count)
        break
    if count == N - 1:
        print(-1)
        break

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input())-1 for _ in range(n)]
visit=[False]*n
cnt=0
nxt=0
for _ in range(n):
    visit[nxt]=True    

    #ボタン2にたどり着いた
    if nxt==1:
        break

    nxt=a[nxt]

    #ループしている到達不能！
    if visit[nxt]:
        cnt=-1
        break

    cnt+=1
    
print(cnt)

Submission status: Accepted

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

cnt = 0
idx = 0

while True :
    x = lst[idx]
    cnt += 1
    if x == 2:
        print(cnt)
        exit()
    idx = x - 1
    if cnt > N:
        print(-1)
        exit()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def resolve():
    # 整数 1 つ
    n = int(input())
    # 整数複数個
    # a, b = map(int, input().split())
    # 整数 N 個 (改行区切り)
    A = [int(input()) for i in range(n)]
    # 整数 N 個 (スペース区切り)
    # N = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    # A = [list(map(int, input().split())) for i in range(H)]

    Dic = {i:A[i-1] for i in range(1, n+1)}

    cnt = 0
    now = 1
    rout = []
#    while now not in rout:
    for _ in range(n):
        rout.append(now)
        now = Dic[now]
        cnt += 1
        if now == 2:
            break

    if now == 2:
        print(cnt)
    else:
        print("-1")

resolve()

Submission status: Accepted

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

ans = 0
now = 1
flag = False
for _ in range(n):
    ans += 1
    now = a[now - 1]
    if now == 2:
        flag = True
        break

print(ans) if flag else print(-1)

Submission status: Accepted

Solution code:
N = int(input())

buttons = [int(input()) for _ in range(N)]
m_dict = {}
index = 1
flag = True

while True:
    if index-1 in m_dict:
        flag = False
        break
    elif index == 2:
        break
    m_dict[index-1] = 1
    index = buttons[index-1]

if flag is True:
    print(len(m_dict))
else:
    print(-1)

Submission status: Accepted

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

b = 1
s = 0
move = []

while True :
    move.append(b)
    b = a[b - 1]
    s += 1
    if b == 2 :
        print(s)
        exit(0)
    if n < s :
        print(-1)
        exit(0)

Submission status: Accepted

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

ans = 1
x = 0
while True:
    if a[x] == 2:
        print (ans)
        exit ()

    if ans > len(a):
        print (-1)
        exit ()

    x = a[x]-1
    ans += 1

Submission status: Accepted

Solution code:
n = int(input())
A = [int(input()) for _ in range(n)]
count = 0
i = 1
for _ in range(n):
    i = A[i - 1]
    count += 1
    if i == 2:
        print(count)
        exit()
print(-1)

Submission status: Accepted

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

i = 1
ans = 0
while True:
    if a[i-1] == -1:
        print(-1)
        break
    ni = a[i-1]
    a[i-1] = -1
    i = ni
    ans +=1
    if i==2:
        print(ans)
        break

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def inputI(): return int(input().strip())
def inputS(): return input().strip()
def inputIL(): return list(map(int,input().split()))
def inputSL(): return list(map(str,input().split()))
def inputILs(n): return list(int(input()) for _ in range(n))
def inputSLs(n): return list(input().strip() for _ in range(n))
def inputILL(n): return [list(map(int, input().split())) for _ in range(n)]
def inputSLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def Yes(): print("Yes"); return
def No(): print("No"); return

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def Base_10_to_n(X, n):
  if X//n:
    return Base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def Base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N = inputI()
a = [0]+inputILs(N)

now = 1
ans = 0
flag = [0 for i in range(N+1)]
while True:
  ans += 1
  now = a[now]
  if flag[now] == 1:
    print(-1)
    exit()
  flag[now] = 1
  if now == 2:
    print(ans)
    exit()

Submission status: Accepted

Solution code:
n = int(input())
l = []
i = 1
s = 0
for _ in range(n):
  l.append(int(input()))
#print(l)
while True:
  j = l[i-1]
  #print(j, i, l[i-1])
  s += 1
  if j == 2:
    print(s)
    exit()
  if s == n:
    print(-1)
    exit()
  i = j

Submission status: Accepted

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

now = a[0]
cnt = 0

while cnt <= n:
    cnt += 1
    if now == 2:
        print(cnt)
        exit()
    now = a[now-1]

print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
pushed = [False] * N
pushed[0] = True
button = 0
count = 0
while True:
    count += 1
    button = A[button] - 1
    if button == 1:
        print(count)
        exit()
    if pushed[button]:
        print(-1)
        exit()
    pushed[button] = True

Submission status: Accepted

Solution code:
n = int(input())
al = []
for i in range(n):
  a = int(input())
  al.append(a)
count = 0
i = 0
while (True):
  i = al[i] - 1
  count += 1
  if i == 1:
    break
  if count > n:
    break
if count > n:
  print('-1')
else:
  print(count)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
start = 0
cnt = 0
for i in range(n):
  nxt = a[start] - 1
  cnt += 1
  if nxt == 1:
    print(cnt)
    quit()
  start = nxt
print(-1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    a=[int1(input()) for i in range(N)]
    used=[False]*N
    v=0
    c=0
    while True:
        used[v]=True
        c+=1
        v=a[v]
        if used[v]:
            print(-1)
            exit()
        if v==1:
            print(c)
            exit()

if __name__ == '__main__':
    main()

Submission status: Accepted

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

count = 0
pos = 1
for n in range(N):
    count += 1
    if a_list[pos-1]==2:
        print(count)
        break
    pos = a_list[pos-1]
    
if a_list[pos-1]!=2:
    print(-1)

Submission status: Accepted

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

#n = 10
#a = [10,0,2,3,4,5,6,7,8,9]

a.insert(0,0)
i = 1
ans = 0
for _ in range(n+1):
  ans += 1
  i = a[i]
  if i == 2:
    break
else:
  ans = -1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
btn = list(int(input()) for i in range(n))
push = set()
ans = 0
x = 1
while x != 2:
    if x in push:
        ans = -1
        break
    push.add(x)
    x = btn[x-1]
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    n=int(input())
    l=[int(input()) for i in range(n)]
    light=0
    cnt=0
    while True:
        if l[light]==2:
            cnt+=1
            print(cnt)
            break
        else:
            if cnt>n:
                print(-1)
                break
            else:
                light=l[light]-1
                cnt+=1
            
resolve()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    n=int(input())
    edge = [[] * n for i in range(n)] # rangeに頂点の数。繋がっている頂点を投入するリスト
    for i in range(n): # rangeに辺の数
        x, y = i,int(input())
        y = y - 1
        edge[x].append(y)
    sagasu=0
    cnt=0
    while True:
        a=edge[sagasu]
        if a==[1]:
            print(cnt+1)
            break
        else:
            if cnt>n:
                print(-1)
                break
            else:
                cnt+=1
                sagasu=a[0]
resolve()

Submission status: Accepted

Solution code:
N=int(input())
a=[int(input()) for i in range(N)]
cnt=0
tgt=0
while tgt!=1:
    tgt=a[tgt]-1
    cnt+=1
    if cnt>N+1:
        print(-1)
        exit()
print(cnt)