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 -*-

n=int(input())
a=[int(input()) for _ in range(n)]
b=[0 for _ in range(n)]

cnt=0
idx=0
while True:
    if n==0 or b[idx]==1:
        print(-1)
        break
    elif a[idx]==2:
        print(cnt+1)
        break
    b[idx]=1
    idx=a[idx]-1
    cnt+=1
    n-=1

Submission status: Accepted

Solution code:
N=int(input())
a_list=[]
exists=False
for _ in range(N):
    a = int(input())
    a_list.append(a)
    if a == 2:
        exists = True
if not exists:
    print(-1)
    exit()

curr = 0
already = set()
ans=0
while True:
    nexthop = a_list[curr] - 1
    if nexthop in already:
        print(-1)
        exit()
    already.add(nexthop)
    curr = nexthop
    ans+=1
    if nexthop == 1:
        print(ans)
        exit()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import itertools

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

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
n=int(input())
a=[]
p=1
for i in range(n):
    a.append(int(input()))
for i in range(n-1):
    p=a[p-1]
    if p==2:
        print(i+1)
        quit()
print(-1)

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest

def resolve():
    n = int(input())
    a = [int(input()) for _ in range(n)]

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

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


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3
3
1
2"""
        output = """2"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """4
3
4
1
2"""
        output = """-1"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """5
3
3
4
2
4"""
        output = """3"""
        self.assertIO(input, output)

if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Accepted

Solution code:
N=int(input())
K=[]
for _ in range(N):
  K.append(int(input()))
L=[1]
for i in range(1,N):
  L.append(K[L[i-1]-1])
if 2 in L:
  print(L.index(2))
else:
  print(-1)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc065/tasks/abc065_b
n = int(input())
nums = []
for i in range(n):
    nums.append(int(input()))

done = set()
b = 0
ans = 0
while True:
    if b == 1:
        print(ans)
        break
    if b in done:
        print(-1)
        break
    done.add(b)
    ans += 1
    b = nums[b] - 1

Submission status: Accepted

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

count = 1
now = 1
# print("lightning: {}".format(now))
while count < len(a):
    now = a[now-1]
    # print("lightning: {}".format(now))
    if now == 2:
        print(count)
        exit()
    count += 1

print('-1')

Submission status: Accepted

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

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

Submission status: Accepted

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

record = set()
pos = 1
count = 0

while True:
    count += 1
    pos = a_l[pos-1]
    if pos == 2:
        print(count)
        break
    elif pos in record:
        print(-1)
        break
    record.add(pos)

Submission status: Accepted

Solution code:
N=int(input())
a=[]
for i in range(N):
  a.append(int(input())-1)
flg=False
s=0
ans=0
for i in range(N):
  ans+=1
  if a[s]==1:
    flg=True
    break
  s=a[s]
if flg: print(ans)
else: print(-1)

Submission status: Accepted

Solution code:
n = int(input())

dic = {}
for i in range(n):
    #a_L.append(input())
    dic[i+1] = int(input())

ans = 0
b = 1
for _ in range(n+1):
    b = dic[b]
    ans += 1
    if b == 2:
        print(ans)
        exit()

print(-1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
52min 40sec
"""
# グラフの最短経路問題っぽい。
# 光ったボタンを後になってから押すことは、
# 最短経路においてはなさそう。
# 幅優先探索で書けばよさそう。
# よく考えると1回ボタンを押すと、
# 次のボタンが必ず1個だけ光るから、分岐しない。

import queue

N_INF = pow(10, 6)

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

min_cost_list = [N_INF for i in range(N)]
lightened_botton_queue = queue.Queue()

def press_botton(botton_no):
    now_cost = min_cost_list[botton_no]
    if min_cost_list[a_list[botton_no]] == N_INF:
        min_cost_list[a_list[botton_no]] = now_cost+1
        lightened_botton_queue.put(a_list[botton_no])
    return

def main():
    lightened_botton_queue.put(0)
    min_cost_list[0] = 0
    while not lightened_botton_queue.empty():
        press_botton(lightened_botton_queue.get())
    answer = int()
    if min_cost_list[1] != N_INF:
        answer = min_cost_list[1]
    else:
        answer = -1
    print(answer)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

pos = 1
route = []
success = False
"""
while 1:
    route.append(pos)
    pos = a[pos - 1]
    if pos == 2:
        print(len(route))
        break
        
    if pos in route:
        print(-1)
        break
"""
for i in range(N):
    pos = a[pos - 1]
    if pos == 2:
        success = True
        print(i+1)
        break
if not(success):
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())

A = []
for i in range(n):
    A += [int(input())]
    
i = 0
cnt = -1

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

    if i == 1:
        cnt = j
        break

print(cnt)

Submission status: Accepted

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

cnt = 0
f = [False]*n
f[0] = True
now = 0
for i in range(n):
    if  now == 1:
        break

    cnt += 1
    f[a[now]-1] = True
    now = a[now]-1

print(cnt if f[1] else -1)

Submission status: Accepted

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

b = a[0]
cnt = 1

while b != 2 and cnt <= n:
    b = a[b-1]
    cnt += 1
if b == 2:
    print(cnt)
else:
    print(-1)

Submission status: Accepted

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

visited = set()
count = 0
next = 1
while True:
  count += 1
  visited.add(next)
  next = a[next-1]
  if next == 2:
    print(count)
    exit(0)
  if next in visited:
    print(-1)
    exit(0)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import deque
n=int(input())
blist=deque([int(input()) for a in range(n)])
vlist=1
count=0
while True:
    if count>n:
        print(-1)
        break
    if 2 == vlist:
        print(count)
        break
    vlist=blist[vlist-1]
    count+=1

Submission status: Accepted

Solution code:
N=int(input())
b=list(int(input()) for i in range(N))

n=0
ans=0
for j in range(N+1):
    n=b[n]-1
    ans += 1
    if n==1:
        break
if ans<N+1:
    print(ans)
else:
    print(-1)

Submission status: Accepted

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

push = [False] * N

ans = 0
i = 0
while True:
    ans += 1
    if a[i] == 2:
        break
    if push[i]:
        ans = -1
        break
    push[i] = True
    i = a[i] - 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
used = set()
bot = [int(input()) for i in range(n)]
bot.insert(0,0)
here = 1
used.add(1)
cnt = 0
while True:
    if here == 2:
        print(cnt)
        exit()
    elif bot[here] not in used:
        used.add(bot[here])
        here = bot[here]
        cnt += 1
    else:
        print(-1)
        exit()

Submission status: Accepted

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

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

print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a_list= []
for i in range(N):
    a_list.append(int(input()))
flag = False
target = 1
push_count = 0
while flag == False and push_count <= N:
    target = a_list[target - 1]
    push_count += 1
    if target == 2:
        print(push_count)
        flag = True
if flag == False:
    print(-1)

Submission status: Accepted

Solution code:
import sys,os
from collections import defaultdict, deque
from math import ceil, floor
if sys.version_info[1] >= 5:
    from math import gcd
else:
    from fractions import gcd
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    MOD = 10**9+7

    N = II()
    A = [0]*N
    pushed = [False]*N
    for i in range(N):
        A[i] = II()
    count = 0
    n = 1
    while True:
        pushed[n-1] = True
        n = A[n-1]
        count += 1
        if n == 2:
            print(count)
            return
        elif pushed[n-1]:
            print(-1)
            return


    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
icase=0
if icase==0:
    n=int(input())
    a=[]
    for i in range(n):    
        ai=int(input())
        a.append(ai)
    icnt=0
    i=1
    while icnt<n:
        icnt=icnt+1
        i=a[i-1]    
#        print("i:",i,a[i-1])
        if i==2:
            print(icnt)
            icnt=-10
            break
    if icnt!=-10:
        print(-1)

Submission status: Accepted

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

ans = -1
num = 1
cnt = 0
for _ in range(n):
    num = list_a[num-1]
    cnt += 1
    if num == 2:
        ans = cnt
        break
    if cnt == n+1:
        break

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
a = []
for i in range(N):
    a.append(int(input()))
# ここまでが入力

b = [0 for _ in range(N)]   # 要素b[n]には、ボタンb[n]を押したことがあれば 1 なければ 0 が格納
c = 1   # ついているボタンの数を格納する変数
counter = 0     # 押したボタンの回数

while c != 2:
    if b[c-1] == 1:      # ボタンｃが押されたことがある場合
        counter = -1
        break
    b[c-1] = 1      # リストbにボタンｃが押されたことを記録させる
    c = a[c-1]      # ボタンを押して次のボタンが光る
    counter += 1

print(counter)

Submission status: Accepted

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

count = 0
num = 0

for x in range(N):
  if a[num] == 2:
    count += 1
    print(count)
    break
  elif a[num] != 2:
    count += 1
    num = a[num] - 1
    if count == N:
      print(-1)
    else:
      continue

Submission status: Accepted

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

Submission status: Accepted

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

count = 0
index = 0

while count < n:
  count += 1
  if array[index] == 1:
    break
  else:
    index = array[index]

if count != n:
  print(count)
else:
  print(-1)

Submission status: Accepted

Solution code:
*A, = map(int, open(0).read().split())
N = A[0]
visited = [0]*(N+1)

cnt = 0
a = 1
while True:
    a = A[a]
    cnt += 1
    if a == 2:
        print(cnt)
        break
    if visited[a]:
        print(-1)
        break
    visited[a] = True

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np


def read():
    N = int(input().strip())
    A = [-1]
    for _ in range(N):
        a = int(input().strip())
        A.append(a)
    return N, A

def solve(N, A):
    i = 1
    for n in range(1, N+1):
        i = A[i]
        if i == 2:
            return n
    return -1

if __name__ == '__main__':
    inputs = read()
    print(solve(*inputs))

Submission status: Accepted

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

    is_not_found = True
    cnt = 1
    idx = a_list[0] - 1
    while is_not_found:
        if idx == 1:
            is_not_found = False
            print(cnt)
        elif cnt >= N:
            is_not_found = False
            print(-1)
        
        idx = a_list[idx] - 1
        cnt += 1


if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
a, b = [0]*n, [False]*n
b[0] = True
for i in range(n):
    a[i] = int(input())
count = 1
light = a[0]

while light != 2:
    b[light-1] = True
    light = a[light-1]
    count += 1
    if b[light-1]:
        print(-1)
        exit(0)
print(count)

Submission status: Accepted

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

    on = [False] * N
    x = 0
    count = 0
    while x != 1:
        c = A[x]
        if on[c]:
            print(-1)
            return
        on[c] = True
        x = c
        count += 1
    
    print(count)

main()

Submission status: Accepted

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

b = 1
cnt = 0
while cnt <= 100000:
  b = a[b-1]
  cnt += 1
  if b == 2:
    break
  
if cnt > 100000:
  print(-1)
else:
  print(cnt)

Submission status: Accepted

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

    count = 0
    cur   = 0
    nxt   = 0

    find = False

    for i in range(2*N):
        count += 1

        if switches[cur] == 2:
            find = True
            print(count)
            break

        nxt = switches[cur] - 1

        if switches[nxt] - 1 == cur:
            find = True
            print(-1)
            break

        cur = nxt
    if find == False:
        print(-1)

main()

Submission status: Accepted

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

A = -1
light = 1
for j in range(N):
  light = a[light - 1]
  if light == 2:
    A = j + 1
    break
  


print(A)

Submission status: Accepted

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

prev = a[0]
ans = 1

while True:
    if prev == 2 or ans > N:
        break
    else:
        prev = a[prev-1]
        ans += 1

print(ans if ans <= N else -1)

Submission status: Accepted

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

visited = [False]*n
i = 0
ans=0
f = False
while visited[i]==False:
    if i == 1:
        print(ans)
        f = True
        break
    ans+=1
    visited[i]=True
    i = a[i]-1
if not f:
    print(-1)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N=int(input())
mylist=[]
j=0
n=0
for i in range(N):
  mylist.append(int(input()))
  
for i in range(N):
  if n==1:
    print(j)
    break
  j=j+1
  n=mylist[n]-1
  if i==N-1:
  	print("-1")

Submission status: Accepted

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

visit = [-1, ] * N
i = 0
s = 0
while (visit[i] == -1):
    visit[i] = s
    s += 1
    i = A[i]
print(visit[1])

Submission status: Accepted

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

visited = set()
res = 0
cur = 1
while True:
    if cur == 2:
        print(res)
        exit()
    if cur in visited:
        print(-1)
        exit()
    visited.add(cur)
    cur = button[cur] 
    res += 1

Submission status: Accepted

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

tmp = 0
con = 0
for i in range(N):
    if btn[tmp] == 2:
        con += 1
        print(con)
        break
    
    elif btn[tmp] != 0:
        tmp2 = btn[tmp] - 1
        btn[tmp] = 0
        tmp = tmp2
        con += 1
    
    else:
        print(-1)
        break

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
a =[-1]+ [int(input())for _ in range(n)]
visited = [0]*(n+1)

now = 1
while True :
    if visited[now] == 1:
        ans = -1
        break
    visited[now] = 1
    
    if a[now] == 2:
        ans +=1
        break
    ans+=1
    now = a[now]
print(ans)

Submission status: Accepted

Solution code:
# ABC 065: B – Trained?
n = int(input())
a = [int(input()) for _ in range(n)]

lightning = 0

for k in range(n):
    lightning = a[lightning] - 1

    if lightning == 1:
        print(k + 1)
        break
else:
    print(-1)

Submission status: Accepted

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

light = 1
goal = 2
for i in range(1, 10**6):
    light = A[light]
    if goal == light:
        print(i)
        exit()
print(-1)

Submission status: Accepted

Solution code:
n, *A = map(int, open(0).read().split())
x = 0
for i in range(n):
  A[x], x = 0, A[x]-1
  if x == -1:
    print(x)
    exit()
  if x == 1:
    print(i+1)
    exit()

Submission status: Accepted

Solution code:
n, *A = map(int, open(0).read().split())
B = [0] * len(A)
x = 0
B[0] = 1
for i in range(n):
  x = A[x]-1
  if B[x]:
    print(-1)
    exit()
  if x == 1:
    print(i+1)
    exit()
  B[x] = 1

Submission status: Accepted

Solution code:
n=int(input())
arr=[int(input())-1 for _ in range(n)]
step = 0
curr=0
while True:
    if curr == 1:
        print(step)
        break
    if step>=n:
        print(-1)
        break
    curr = arr[curr]
    step += 1

Submission status: Accepted

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

idx = 0
flg = 0
for j in range(n):
  idx = ls[idx]-1
  if idx == 1:
    flg = 1
    break
if flg == 1:
  print(j+1)
else:
  print(-1)

Submission status: Accepted

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

bottom = 1
answer = 0

while bottom != 2:
    bottom = a[bottom-1]
    answer += 1
    if answer >= 10**5+9:
        print(-1)
        exit()
    
print(answer)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
button = [int(input()) for _ in range(N)]
current_button = button[0]
ans = 1
while True:
    if current_button == 2:
        print(ans)
        exit()
    current_button = button[current_button-1]
    ans += 1
    if ans >= 10**5 + 10:
        print(-1)
        exit()

Submission status: Accepted

Solution code:
N = int(input())
#N, M = map(int, input().split())
#A = list(map(lambda x: int(x)*(-1), input().split()))
#X = list(map(int, input().split()))
X = [int(input()) for i in range(N)]
#C = [list(map(int, input().split())) for i in range()]

pointer = 1
push = 0
for i in range(N):
    pointer = X[pointer-1]
    push += 1
    if pointer == 2:
        print(push)
        exit()
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
p = [0]
for i in range(n):
    p.append(int(input()))
kar = 1
ans = 0
c = 0
while True:
    if kar == -1:
        print(-1)
        exit()
    elif kar == 2:
        print(ans)
        exit()
    else:
        c = kar
        kar = p[kar]
        p[c] = -1
        ans += 1

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    a = [0 for i in range(N)]
    for i in range(N):
        a[i] = int(input())
    now = 1
    for i in range(N):
        if a[now - 1] == 2:
            break
        elif i == N - 1:
            i = -2
        else:
            now = a[now - 1]
        #print('{}: {}'.format(i, now))
    print(i + 1)
main()

Submission status: Accepted

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

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

print(-1)

Submission status: Accepted

Solution code:
*a, = map(int, open(0).read().split())
b = a[1]
for i in range(a[0]):
    if b == 2:
        print(i+1)
        exit()
    b = a[b]
print(-1)

Submission status: Accepted

Solution code:
*a, = map(int, open(0).read().split())
b = a[1]
l = []
for i in range(a[0]):
    if b == 2:
        print(i+1)
        exit()
    b = a[b]
print(-1)

Submission status: Accepted

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

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

ans = 0
now = 0
for _ in range(n):
    now = a[now] -1 
    ans += 1
    if(now == 1):
        print(ans)
        exit()

print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=[0]
for _ in range(n):
    a.append(int(input()))
b=[0]*(n+1)
i=1
ans=0
while b[i]==0 and i!=2:
    b[i]=1
    i=a[i]
    ans+=1
print(ans if i==2 else -1)

Submission status: Accepted

Solution code:
N = int(input())

a = []

for i in range(N):
    a.append(input())

ind = 0
i = 0
flag = 0
while i < N:
    if a[ind] == "2":
        flag = 1
        i += 1
        break
    else:
        ind = int(a[ind])-1
    
    i += 1

if flag == 1:
    print(i)
else:
    print("-1")

Submission status: Accepted

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

x=1
for i in range(N):
  if(x==2):
    print(i)
    exit()
  x=a[x-1]
print("-1")

Submission status: Accepted

Solution code:
N = int(input())
A=[]
l=[1]
ans=0
for i in range(N):
    A.append(int(input()))
for i in range(N):
    l.append(A[l[i]-1])
    if l[i+1]==2:
        ans=i+1
        break
if ans!=0:
    print(ans)
else:
    print(-1)

Submission status: Accepted

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

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

cnt = 0
b = 1
ans = 0

for j in range(n+1):
    cnt += 1
    b = a[b]
    
    if b == 2:
        ans = 1
        break
if ans == 1:
    print(cnt)

else:
    print("-1")

Submission status: Accepted

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

for i in range(n+1):
    k=num[k]
    count+=1
    if k==2:
        ans=1
        break
if ans==1:
    print(count)
else:
    print("-1")

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,boundary=1,search=[],replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,boundary=1,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
def show2d(g,h,w):
    for i in range(h):show(g[i*w:i*w+w])

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True

n=I()
a=[0]*n
for i in range(n):
    a[i]=I()-1
j=0
c=0
while j!=1 and c<10**6:
    c+=1
    j=a[j]
print(c if c<10**5 else -1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def solve():
    N = Scanner.int()
    A = [0] * N
    for i in range(N):
        A[i] = Scanner.int()
    visited = [False] * N
    p = 0
    cnt = 0
    while p != 1:
        if visited[p] == True:
            print(-1)
            return
        visited[p] = True
        p = A[p] - 1
        cnt += 1
    print(cnt)


def main():
    # sys.stdin = open("sample.txt")
    solve()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

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

step = 0
t = 0
seen = {0}
while True:
    t = a[t]
    step += 1
    if t == 1:
        print(step)
        sys.exit()
    if t in seen:
        print(-1)
        sys.exit()
    seen.add(t)

Submission status: Accepted

Solution code:
N=int(input())
A={i:int(input()) for i in range(1,N+1)}

flag=0
k=1
for i in range(N):
    k=A[k]
    if k==2: flag=1; break

if flag: print(i+1)
else: print(-1)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
n=int(input())
num=[0]
ans=0
count=0
k=1
for i in range(n):
    a=int(input())
    num.append(a)

for i in range(n+1):
    k=num[k]
    count+=1
    if k==2:
        ans=1
        break
if ans==1:
    print(count)
else:
    print("-1")

Submission status: Accepted

Solution code:
n = int(input())
A = []
i = 0 
while i < n:
    A.append(int(input())-1)
    i += 1
used_list = [0]
count = 0
t = 0
while count < n:
    t1 = A[t] 
    count += 1
    if t1 == 1:
        break
#    if t1 in used_list:
#        count = -1
#        break
    used_list.append(t1)
    t = t1
if t1 != 1:
    count = -1
print(count)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for i in range(N)]
i=0
j=0
cnt=0
while True:
    if a[j]==2:
        cnt+=1
        print(cnt)
        break
    elif cnt>N:
        print(-1)
        break
    else:
        cnt+=1
        i+=1
        j=a[j]-1

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
now = 1
cnt = 0
while now != 2 and cnt <= N:
    now = a[now-1]
    cnt += 1
if cnt > N:
    print(-1)
else:
    print(cnt)