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:
n = int(input())
a = [0] + [int(input()) for i in range(n)]
cnt = 1
next_a = a[1]

if a[1] == 2:
    print(cnt)

else:
    while cnt <= 10**5:
        next_a = a[next_a]
        cnt += 1
        if next_a == 2:
            break

    if cnt <= 10**5:
        print(cnt)
    else:
        print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

num=l[0]
cnt=0
for i in range(10**5):
  if num==2:
    cnt+=1
    break
  else:
    num=l[num-1]
    cnt+=1
    
if cnt==10**5:
  cnt=-1
  
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
l = [0 for _ in range(n)]
already = set()
next = 1
c = 0
for i in range(n):
  a = int(input())
  l[i] = a
while c <= n:
  next = l[next-1]
  c += 1
  if next == 2:
    print(c)
    break
  elif next in already:
    print(-1)
    break
  already.add(next)

Submission status: Accepted

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

index = 0
count = 0
for i in range(N):
    b = al[index]
    count += 1
    if b == 2:
        break
    index = b - 1

if b != 2:
    count = -1

print(count)

Submission status: Accepted

Solution code:
N = int(input())
As = [int(input()) for i in range(N)]
visited=[False]*N
c = 0
now = 0
while True:
    if visited[now]:
        c = -1
        break
    visited[now] = True
    c+=1
    now = As[now]-1
    if now == 1:
        break
print(c)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    N = int(readline())
    seq = []

    for _ in range(N):
        a = int(readline())
        a -= 1
        seq.append(a)

    cur = 0

    for i in range(1, 10 ** 6):
        cur = seq[cur]
        if cur == 1:
            return print(i)

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = []
for i in range(N):
  A.append(int(input())-1)
    
ans = -1
push = 0
count = set()
 
for i in range(N+1):
 
    if A[push] == 1:
        ans = i+1
        break
        
    elif A[push] in count:
      break
      
    else:
      count.add(push)
      push = A[push]
        
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = []
for i in range(N):
  A.append(int(input())-1)
    
ans = -1
push = 0
count = [False]*N
 
for i in range(N+1):
 
    if A[push] == 1:
        ans = i+1
        break
        
    elif count[push]:
      break
      
    else:
        count[push] = True
        push = A[push]
        
      
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = []
for i in range(N):
  A.append(int(input())-1)
    
#A.insert(0, 0)
ans = -1
push = 0

for i in range(N+1):

    if A[push] == 1:
        ans = i+1
        break
        
    else:
        push = A[push]
      
print(ans)

Submission status: Accepted

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

for i in range(1, n+2):
    
    if a[push] == 2:
        ans = i
        break
        
    else:
        push = a[push]
      
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
al = []
for i in range(n):
    a = int(input())
    al.append(a)
 
al.insert(0, 0)
ans = -1
push = 1
for i in range(1, n+2):
    light = al[push]
    push = light
    if light == 2:
        ans = i
        break
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
#x, a, b = map(int, input().split())
#l = list(map(int,input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
al = []
for i in range(n):
    a = int(input())
    al.append(a)

al.insert(0, 0)
ans = -1
push = 1
for i in range(1, n+2):
    light = al[push]
    push = light
    if light == 2:
        ans = i
        break
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
d = []
visited = [False for _ in range(N+1)]
for _ in range(N):
  d.append(int(input())-1)

i = 0
cnt = 0
while True:
  if i == 1:
    break
  elif cnt >= N:
    cnt = -1
    break
  elif visited[i]:
    cnt = -1
    break
  else:
    visited[i] = True
    cnt += 1
    i = d[i]
  
print(cnt)

Submission status: Accepted

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


ans = -1
memo = 0
light = 1

for i in range(n):
    if light == 2:
        ans = memo
        break
    light = a[light-1]
    memo += 1


print(ans)

Submission status: Accepted

Solution code:
import sys

n = int(input())
A = list(map(int, sys.stdin.readlines()))

index = 0
past_index = list()
found = False

for i in range(len(A)):
    if index == 1:
        print(i)
        found = True
        break
    index = A[index]-1

if not found:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input())-1 for _ in range(N)]
cnt = 1
next_button = 0
while cnt <= len(A):
    next_button = A[next_button]
    if next_button == 1:
        print(cnt)
        exit()
    cnt += 1
print(-1)

Submission status: Accepted

Solution code:
LI = lambda: list(map(int, input().split()))

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


def main():
    a = 1
    for i in range(N + 1):
        if a == 2:
            print(i)
            return 0
        a = A[a - 1]
    print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for i in range(N)]
i = 0
cnt = 1
cmpr = [0]
while A[i] != 2:
    if A[i] == i + 1:
        print(-1)
        exit()
    i = A[i] - 1
    cmpr.append(i)
    cnt += 1
    if cnt > N:
        print(-1)
        exit()
print(cnt)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**20
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

def resolve():
    N = I()
    a = [I() - 1 for _ in range(N)]

    c = 0
    ans = 0
    is_ok = True
    while True:
        c = a[c]
        ans += 1
        if c == 0 or ans > N:
            is_ok = False
            break
        if c == 1:
            break

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

if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

now = 0
cnt = 0
while A[now] != 2 and cnt <= n:
    now = A[now] - 1
    cnt += 1

if A[now] == 2:
    print(cnt + 1)
else:
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

n = int(input())
l = []
for _ in range(n):
    l.append(int(input()) - 1)

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

Submission status: Accepted

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

# N 1
ans = 0
next_idx = 0
for _ in range(n):
    ans += 1
    next_idx = a_l[next_idx]-1
    if next_idx == 1:
        break
if next_idx != 1:
    ans = -1
print(ans)

Submission status: Accepted

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

flag = True
position = 1

for i in range(n):
    position = a[position-1]
    if position == 2:
        print(i+1)
        flag = False
        break
        
if flag:
    print(-1)

Submission status: Accepted

Solution code:
n=int(input())
ans=0
result=0
s=[]
for _ in range(n):
    s.append(int(input()))
    
pos=s[0]

for i in range(n):
    if pos==2:
        ans+=1
        result+=1
        break
    else:
        pos=s[pos-1]
        ans+=1

if result==0:
    print(-1)
else:
    print(ans)

Submission status: Accepted

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

visited = [False] * n
f = 0
visited[f] = True
cnt = 0
while True:
    cnt += 1
    t = a[f]
    if t == 1:
        flg = True
        break
    if visited[t]:
        flg = False
        break
    visited[t] = True
    f = t
print(cnt) if flg else print(-1)

Submission status: Accepted

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

n = int(input())

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

note = [0] * n
i = 0
step = 0
ret = -1
while True:
    if note[i] == 1:
        break
    if i == 1:
        ret = step
        break
    note[i] = 1
    i = a[i] - 1
    step += 1


print(ret)

Submission status: Accepted

Solution code:
import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline 
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    n = i_input()
    a_list = i_row(n)

    link = [[] for _ in range(n + 1)]

    for i, a in enumerate(a_list):
        if i+1 != 2:
            link[i+1].append(a)
        
    
    dist = [-1] * (n + 1)
    que = deque([1])

    while que:
        v = que.popleft()
        for i in link[v]:
            if dist[i] == -1:
                dist[i] = v
                que.append(i)

    count = 0
    j = 2
    while j != 1:
        j = dist[j]
        if j == -1:
            count = -1
            break
        count += 1
    
    print(count)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

l = [1]
bot = 1
flag = True
for i in range(n):
    bot = a[bot - 1]
    if bot == 2:
        print(i + 1)
        flag = False
        break

if flag:
    print(-1)

Submission status: Accepted

Solution code:
import sys
n = int(input())
a = []
visited = []
for _ in range(n):
  a.append(int(input()))
  visited.append(0)
  
ans = 0
c = 0

for i in range(n):
  ans += 1
  visited[c] = 1
  c = a[c]-1
  if c == 1:
    print(ans)
    sys.exit()
  elif visited[c] == 1:
    break
print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

    tmp = 0

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

    print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys 
N = list(map(int, sys.stdin))
bot = N[1]
for i in range(N[0]):
  if bot == 2:
    print(i+1)
    break
  bot = N[bot]
else:
  print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
a.insert(0, 0)
next = 1
ans = 0
for i in range(N):
    next = a[next]
    ans += 1
    if next == 2:
        print(ans)
        break
else:
    print(-1)

Submission status: Accepted

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

if 2 in a:
    k = 1
    while True:
        t = a[k-1]
        a[k-1] = -1
        k = t
#        print(t)
#        print(a)
        if k == -1:
            break
        elif k == 2:
            break
        
    if k == -1:
        print(-1)
    else:
        print(a.count(-1))
else:
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input());a=[int(input()) for _ in range(n)]
num,cnt=0,1
while a[num]!=2:
  num=a[num]-1
  cnt+=1
  if cnt==n:
    print(-1);exit()
print(cnt)

Submission status: Accepted

Solution code:
import math
import sys
import os
from operator import mul

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")


N = I()
a = [I() for _ in range(N)]
a = list(map(lambda x:x-1,a))

ans = -1

# 訪れる順序、indexは移動回数
route = [0]
# 訪れた番号、高速検索用にhash tableを使う
visited = set([0])
next = a[0]

while True:
    if next in visited:
        loopStart = route.index(next)
        break
    else:
        route.append(next)
        visited.add(next)
        next = a[next]
        
# print(route)
# 番号2のボタンが含まれる   
if 1 in visited:
    ans = route.index(1)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
d = [int(input()) for i in range(N)]
cnt=1
a=d[0]
if a==2:
    print(cnt)
    exit()

for _ in range(N):
    a=d[a-1]
    cnt+=1
    if a==2:
        print(cnt)
        exit()
print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

now = 0
judge = False
ans = 0
for i in range(n):
  ans += 1
  if a[now] == now:
    break
  if a[now] == 1:
    judge = True
    break
  now = a[now]

print(ans if judge else -1)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if len(args) > 0 else [default for _ in range(n)]

sys.setrecursionlimit(1000000)
dire, dire8 = [[1, 0], [0, 1], [-1, 0], [0, -1]], [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets, ALPHABETS = "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD, INF = 1000000007, float("inf")

def main():
    N = I()
    A = IR(N)

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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

log = []
button = 1
count = 0
while button != 2:
    button = a[button-1]
    count += 1
    log.append(button)
    if count == N+1:
        count = -1
        break
print(count)

Submission status: Accepted

Solution code:
n = int(input())

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

loop = [0] * n


if (2 not in a):
    print(-1)
    exit()

tar_index = 0
loop[0] = 1
# 何回目で２に到達するか
count = 0

while True:
    tar_index = a[tar_index] - 1
    #print(count, tar_index)
    count += 1

    if (tar_index == 1):
        print(count)
        exit()

    # 一回行った場所に戻ると、循環してるのでOUT
    if (loop[tar_index] == 1):
        print(-1)
        exit()

    loop[tar_index] = 1

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
from scipy.special import comb
import copy
sys.setrecursionlimit(10**6)


def zz():
    return list(map(int, sys.stdin.readline().split()))


def z():
    return int(sys.stdin.readline())


def S():
    return sys.stdin.readline()[:-1]


def C(line):
    return [sys.stdin.readline() for _ in range(line)]


N = z()
A = []
for i in range(N):
    A.append(z())

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

Submission status: Accepted

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

cnt = 0
now = 1
for i in range(N):
    next = A[now-1]
    cnt += 1
    if next == 2:
        print(cnt)
        exit(0)
    now = next 
print(-1)

Submission status: Accepted

Solution code:
import sys
N = int(input())
a = list()
for i in range(N):
  a.append(int(input()))
i = 0
ans = 1
for _ in range(N):
  next_a = a[i]
  if(next_a == 2):
    print(ans)
    sys.exit()
  else:
    i = next_a-1
    ans += 1
print(-1)

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from functools import reduce
from bisect import bisect_left, insort_left
from heapq import heapify, heappush, heappop

INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))

sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    N = INT()
    A = [INT() for _ in range(N)]

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

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
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 = [INT() for _ in range(N)]

r = 0
cnt = 0
flags = [0] * N
flags[0] = 1
while True:
    r = A[r] - 1
    if flags[r] == 1:
        print(-1)
        break
    else:
        flags[r] += 1
        cnt += 1

    if flags[1] == 1:
        print(cnt)
        break

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
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, bisect_left, bisect_right

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
A = [INT() for i in range(N)]

visited = [False] * N
i = 1
cnt = 0
while 1:
    if visited[i-1] == False:
        visited[i-1] = True
        if i == 2:
            print(cnt)
            exit()
        i = A[i-1]
        cnt += 1
        # i = nex
    elif visited[i-1] == True:
        print("-1")
        exit()

Submission status: Accepted

Solution code:
N=int(input())
A=[]
ans=-1
for i in range(N):
    A.append(int(input()))

num=A[0]
for j in range(N):
    if num==2:
        ans=j+1
        break
    num=A[num-1]
print(ans)

Submission status: Accepted

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

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()


def main():
	n=II()
	A=[II() for _ in range(n)]

	#print(A)

	now=0
	cnt=1
	ans=-1
	for i in range(n+5):
		now=A[now]-1
		if now==1:
			ans=cnt
			break
		elif now==0:
			break
		else:
			cnt+=1
	print(ans)




if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
a = [s-1 for s in a]
index = a[0]
count = 1
flag = False
while(count <= N):
  if index == 1:
    flag = True
    break
  else:
    count += 1
    index = a[index]

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

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
A = list(map(lambda x:x-1, A))
ex = [0]*10**5
light = 0
for i in range(N) :
    if light == 1 :
        print(i)
        exit()
    elif ex[light] == 1 :
        print('-1')
        exit()
    ex[light] = 1
    light = A[light]

print('-1')

Submission status: Accepted

Solution code:
N, *A = map(int, open(0).read().split())

A = [a - 1 for a in A]
cur = 0
cnt = 0
for _ in range(N):
    nxt = A[cur]
    cnt += 1
    if nxt == 1:
        print(cnt)
        break
    cur = nxt
else:
    print(-1)

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
import sys
sys.setrecursionlimit(10000000)
#mod = 10**9 + 7
#mod = 9982443453
mod = 998244353
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n = I()
bottun = [I() for _ in range(n)]
if bottun.count(2) == 0:
    print(-1)
else:
    cnt = 0
    now = 1
    dic = defaultdict(int)
    while True:
        now = bottun[now-1]
        if dic[now] == 1:
            print(-1)
            exit()
        else:
            dic[now] = 1
        cnt += 1
        if now == 2:
            print(cnt)
            exit()

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
A.insert(0,0)
hist = [0 for _ in range(N+1)]
a = 1
cnt = 0
hist[a] = 1
while True:
    cnt += 1
    a = A[a]
    if hist[a]==1:
        cnt = -1
        break
    hist[a] = 1
    if a==2:
        break
print(cnt)

Submission status: Accepted

Solution code:
N=int(input())
L=[]
count=0
t=0
for i in range(N):
	L.append(int(input()))
while(1):
	count+=1
	if count>N+10:
		print(-1)
		exit()
	if L[t]==2:
		print(count)
		exit()
	else:
		t=L[t]-1

Submission status: Accepted

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

seen = set()
up = 1
cnt = 0
while up != 2:
    if up in seen:
        cnt = -1
        break
    seen.add(up)
    up = A[up]
    cnt += 1

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = [0]+[int(input()) for _ in range(n)]
check = [0] * (n+1)
now = 1
cnt = 0
while now != 2:
    if check[now] == 1: break
    cnt += 1
    check[now] = 1
    now = a[now]
print(cnt if now == 2 else -1)

Submission status: Accepted

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

g = [[] for _ in range(n)]
for i, a in enumerate(A):
    g[a-1].append(i)

from collections import deque
q = deque([1])
visit = [-1]*n
visit[1] = 0
while q:
    v = q.popleft()
    for u in g[v]:
        if visit[u] == -1:
            visit[u] = visit[v]+1
            q.append(u)
if visit[0] == -1:
    print(-1)
else:
    print(visit[0])

Submission status: Accepted

Solution code:
n = int(input())
al = [0]*(n+1)
for i in range(n):
    al[i+1] = int(input())
    
curr = 1
for i in range(10**5+1):
    next_pos = al[curr]
    if next_pos == 2:
        print(i+1)
        break
    else:
        curr = next_pos
else:
    print(-1)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    a = [int(input()) for _ in range(N)]
    lst = [False] * N
    i = 1  # 光っているボタン
    cnt = 0
    flag = False

    for _ in range(N):
        lst[i - 1] = True  # 今光っているボタンを記録
        cnt += 1  # 今光っているボタンを押す
        i = a[i - 1]  # 新しく光るボタン

        if i == 2:  # ボタン2が光ったら終了
            flag = True
            break

        if lst[i - 1] == True:  # 新しく光るボタンが過去に光ったことがある
            flag = False
            break

    if flag == True:
        print(cnt)
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

    for _ in range(N):
        cnt += 1
        i = a[i - 1]

        if i == 2:
            flag = True
            break

    if flag == True:
        print(cnt)
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

now = 0
cnt = 0
while cnt <= N:
  now = A[now]
  if now == 1:
    cnt += 1
    print(cnt)
    exit()
  cnt += 1
print(-1)

Submission status: Accepted

Solution code:
N = int (input ())
l = {}
for i in range (N):
  a = int (input ())
  l[i+1] = a
b = 1
x = 0
for i in range (N+1):
  b = l[b]
  x += 1
  if b == 2:
    print (x)
    x = 0
    break
if x != 0:
  print (-1)

Submission status: Accepted

Solution code:
n=int(input())
d={}
for i in range(1, n+1):
  x=int(input())
  d[i] = x
if d[1] == 2:
  print(1)
  exit()
tmp = d[1]
ans=1
for _ in range(n):
  ans+=1
  tmp = d[tmp]
  #print(tmp)
  if tmp == 2:
    print(ans)
    exit()
print(-1)

Submission status: Accepted

Solution code:
#
# abc065 b
#
import sys
from io import StringIO
import unittest


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)


def resolve():
    N = int(input())
    a = [0] + [int(input()) for _ in range(N)]
    A = [0] * (N+1)

    p = 1
    ans = 0
    while True:
        A[p] += 1
        if A[p] == 2:
            ans = "-1"
            break
        ans += 1
        p = a[p]
        if p == 2:
            break

    print(ans)


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

Submission status: Accepted

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

G = [1]
for i in range(N):
    G.append(A[G[-1]-1])
    
ans = 0
for i in G:
    if i==2:
        break
    ans += 1
else:
    ans = -1
    
print(ans)

Submission status: Accepted

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

G = [1]
for i in range(N):
    G.append(A[G[-1]-1])
    
ans = 0
for i in range(N+1):
    if G[i]==2:
        break
    ans += 1
else:
    ans = -1
    
print(ans)