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
stdin = sys.stdin

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

def dfs(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのstackを作成
    dist[start] = 0
    stack = [(0,start)]
    
    while stack:
        cost, cur_node = stack.pop()

        # 未探索のノードをstackに入れる
        for nex_cost, nex_node in graph[cur_node]:
            if dist[nex_node] != INF:
                continue
            else:
                dist[nex_node] = dist[cur_node] + nex_cost
                stack.append((dist[nex_node],nex_node))
                
    return dist

n = ni()
a = [ni() for _ in range(n)]

adj = [[] for _ in range(n)]

for i in range(n):
    adj[i].append((1,a[i]-1))

dist = dfs(adj, n, 0)

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

Submission status: Accepted

Solution code:
N = int(input())
A = [0]
for i in range(N):
    A.append(int(input()))
old = []
bo = 1
ind = 1
while ind <= N:
    if A[bo] == 2:
        print(ind)
        exit()
    else:
        ind += 1
        bo = A[bo]
print(-1)

Submission status: Accepted

Solution code:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


def main():
    N = int(input())
    A = []
    for i in range(N):
        a = int(input())
        A.append(a - 1)

    idx = 0
    used = [0] * N
    ans = 0
    while True:
        if idx == 1:
            break
        if used[idx]:
            print(-1)
            return
        used[idx] = 1
        idx = A[idx]
        ans += 1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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:
n=int(input())
a=[int(input()) for i in range(n)]
b,c=a[0],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:
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:
N=int(input())
A=[int(input()) for _ in range(N)]
b=A[0]
ans=1
for i in range(len(A)):
    if b==2:
        print(ans)
        exit()
    b=A[b-1]
    ans+=1
print(-1)

Submission status: Accepted

Solution code:
N = int(input())

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

now = 0
count = 0
visited = set()

while True:
  now = A[now]
  count += 1
  if now == 1:
    print(count)
    exit(0)
    
  if now in visited:
    print(-1)
    exit(0)
  else:
    visited.add(now)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int( input())
A = [ int( input()) for _ in range(N)]
A = [ a-1 for a in A]
L = [ 0 for _ in range(N)]
L[0] = 1
cnt = 0
now = 0
while True:
    if now == 1:
        break
    now = A[now]
    if L[now] == 0:
        L[now] = 1
        cnt += 1
    else:
        cnt = -1
        break
print(cnt)

Submission status: Accepted

Solution code:
import sys
import math
import collections
import itertools
import array
import inspect

# Set max recursion limit
sys.setrecursionlimit(1000000)


# Debug output
def chkprint(*args):
    names = {
        id(v): k
        for k, v in inspect.currentframe().f_back.f_locals.items()
    }
    print(', '.join(
        names.get(id(arg), '???') + ' = ' + repr(arg) for arg in args))


# Binary converter
def to_bin(x):
    return bin(x)[2:]


def li_input():
    return [int(_) for _ in input().split()]


def gcd(n, m):
    if n % m == 0:
        return m
    else:
        return gcd(m, n % m)


def gcd_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = gcd(v, L[i])

    return v


def lcm(n, m):
    return (n * m) // gcd(n, m)


def lcm_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = lcm(v, L[i])

    return v


# Width First Search (+ Distance)
def wfs_d(D, N, K):
    """
    D: 隣接行列(距離付き)
    N: ノード数
    K: 始点ノード
    """

    dfk = [-1] * (N + 1)
    dfk[K] = 0

    cps = [(K, 0)]
    r = [False] * (N + 1)
    r[K] = True
    while len(cps) != 0:
        n_cps = []
        for cp, cd in cps:
            for i, dfcp in enumerate(D[cp]):
                if dfcp != -1 and not r[i]:
                    dfk[i] = cd + dfcp
                    n_cps.append((i, cd + dfcp))
                    r[i] = True

        cps = n_cps[:]

    return dfk


# Depth First Search (+Distance)
def dfs_d(v, pre, dist):
    """
    v:  現在のノード
    pre: １つ前のノード
    dist: 現在の距離

    以下は別途用意する
    D: 隣接リスト(行列ではない)
    D_dfs_d: dfs_d関数で用いる，始点ノードから見た距離リスト
    """

    global D
    global D_dfs_d

    D_dfs_d[v] = dist

    for next_v, d in D[v]:
        if next_v != pre:
            dfs_d(next_v, v, dist + d)

    return


def sigma(N):
    ans = 0
    for i in range(1, N + 1):
        ans += i
    return ans


class Combination:
    def __init__(self, n, mod):

        g1 = [1, 1]
        g2 = [1, 1]
        inverse = [0, 1]
        for i in range(2, n + 1):
            g1.append((g1[-1] * i) % mod)
            inverse.append((-inverse[mod % i] * (mod // i)) % mod)
            g2.append((g2[-1] * inverse[-1]) % mod)
        self.MOD = mod
        self.N = n
        self.g1 = g1
        self.g2 = g2
        self.inverse = inverse

    def __call__(self, n, r):
        if (r < 0 or r > n):
            return 0
        r = min(r, n - r)
        return self.g1[n] * self.g2[r] * self.g2[n - r] % self.MOD


# --------------------------------------------

dp = None


def main():
    N = int(input())
    A = [int(input()) for _ in range(N)]
    A.insert(0, -1)

    i = 1
    ans = 1
    R = [False] * (N + 1)
    while True:
        R[i] = True

        if A[i] == 2:
            print(ans)
            return

        if R[A[i]]:
            print(-1)
            return

        i = A[i]
        ans += 1


main()

Submission status: Accepted

Solution code:
n=int(input())
a=list(int(input())-1 for _ in[0]*n)
s=0
c=0
while s!=1 and c<n:
    c+=1
    s=a[s]
print(c if c<n else -1)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
start = a[0]
counting = 1
coreect = 0
if start == 2:
    print(counting)
    coreect = 1

else:
    while N >= 1:
        
        N -= 1
        counting += 1
        start = a[start-1]
        if start == 2:
            coreect = 1
            print(counting)
            break

if coreect != 1:
    print(-1)

Submission status: Accepted

Solution code:
#65b
n = int(input())
a = [int(input()) for _ in range(n)]
x=1

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

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

visited = [0]*(n+1)
visited[1] = 1
cur = 1
ans = 0
while True:
    cur = a[cur]
    ans += 1
    visited[cur] += 1
    if visited[cur] > 1:
        print(-1)
        break
    elif cur == 2:
        print(ans)
        break

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n = int(input())
buttons = [int(input()) - 1 for i in range(n)]
button = 0
for count in range(1, n+1):
    button = buttons[button]
    if button == 1:
        print(count)
        exit()
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
buttons = [input() for i in range(n)]
buttons_int = [int(b) - 1 for b in buttons]
button = 0
for count in range(1, n+1):
    button = buttons_int[button]
    if button == 1:
        print(count)
        exit()
print(-1)

Submission status: Accepted

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

f=True
s=1
for i in range(n):
  if s==2:
    print(i)
    f=False
    break
  s=d[s]
if f:
  print(-1)

Submission status: Accepted

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

trace = {1}
p = a[0]
ans = 1
while p != 2:
    if p in trace:
        ans = -1
        break
    trace.add(p)
    p = a[p - 1]
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
import sys
N=int(input())
data=[]
for i in range (N):
    X=int(input())
    data.append(X)
button=data[0]
count=1
while button!=2:
    button=data[button-1]
    count+=1
    if count>=N:
        print(-1)
        sys.exit()
print(count)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, [input() for _ in range(n)]))
j = 0
ans = -1
for i in range(1, n + 1):
    if a[j] == 2:
        ans = i
        break
    j = a[j] - 1
print(ans)

Submission status: Accepted

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

print(ans)

Submission status: Accepted

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

checked = set()
if a_list[0] == 2:
    print(1)
    exit()

checked.add(a_list[0])
count = 1
btn = a_list[0]
for i in  range(1, N):
    ai = a_list[btn-1]
    count +=1
    if ai in checked:
        print(-1)
        exit()
    else:
        if ai == 2:
            print(count)
            exit()
        else:
            checked.add(ai)
            btn = ai
print(-1)

Submission status: Accepted

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

def main():
    n = int(input())
    a_list = [int(input()) for _ in range(n)]
    a_list.insert(0, 0)

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
a = [int(input()) for i in range(N)]
check=[False for i in range(N)]
pos=0
cnt=0

while True:
    if(pos==1):
        print(cnt)
        break
    elif (check[pos]):
        print(-1)
        break
    else:
        check[pos]=True
        pos=a[pos]-1   
        cnt+=1

Submission status: Accepted

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

button = 1
i = 0

while True:
    if button == 2:
        print(i)
        break
    if i > N:
        print(-1)
        break

    button = a[button]
    i += 1

Submission status: Accepted

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

button = 1
i = 0

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

Submission status: Accepted

Solution code:
N = int(input())
a = []
for _ in range(N):
    a.append(int(input()))
index = 0
ans = 0
while N > 0:
    index = a[index]-1
    if (index == 1):
        print(ans+1)
        quit()
    N-=1
    ans+=1
print(-1)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys,heapq,bisect,math,itertools,string
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
AtoZ = [chr(i) for i in range(65,65+26)]
atoz = [chr(i) for i in range(97,97+26)]

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

now = 1
count = 0
while True:
	if now == 2:
		print(count)
		break
	elif now == -1:
		print(-1)
		break
	bef = now
	now = aa[now]
	aa[bef] = -1
	count += 1

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

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

already_nums = set()
push_count = 0
i = 0
while i != 1:
    if i not in already_nums:
        already_nums.add(i)
        i = a[i]-1
        push_count += 1
    else:
        print(-1)
        sys.exit()
print(push_count)

Submission status: Accepted

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

i = 1
z = 0
count = 0
while z <N:
    i = a[i-1]
    count+=1
    z+=1
    if i ==2:
        print(count)
        break
else:
    print(-1)

Submission status: Accepted

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

x = 1
count = 0
while True:
    if x == 2:
        print(count)
        break
    if a[x] is None:
        print(-1)
        break
    else:
        count += 1
        temp = a[x]
        a[x] = None
        x = temp

Submission status: Accepted

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

light=1
count=0
for i in range(N):
    if light==2:
        print(count)
        quit()
    elif count>0 and light==1:
        print(-1)
        quit()
    else:
        light=A[light-1]
        count+=1
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = []
for i in range(N):
    a.append(int(input()))
b = [0] * N # 通ったかの判定用

i = 1
cnt = 0
while i != 2 and b[i - 1] == 0: # iが2ではない、もしくは通ったことのないルートのとき
    index = i - 1 # 配列の添え字に変換
    b[index] = 1
    i = a[index]
    cnt += 1

if i == 2:
    re = cnt
else:
    re = -1

print(re)

Submission status: Accepted

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

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

print(-1)

Submission status: Accepted

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

next_a = 1
count = 0
while(True):
    #print(next_a)
    tmp = A[next_a-1]
    A[next_a-1] = -1
    next_a = tmp
    count += 1
    if next_a == 2:
        print(count)
        break
    if A[next_a-1] == -1:
        print(-1)
        break

Submission status: Accepted

Solution code:

def main():
    n = int(input())
    lst=[]

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

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

    print(-1)

if __name__ == "__main__":
        main()

Submission status: Accepted

Solution code:
N = int(raw_input())
a = [0]
for i in range(N):
  a.append(int(raw_input()))
i = 0
j = 1
while True:
  nj = a[j]
  i += 1
  if nj==2:
    print i
    break
  elif nj==j or a[nj]==0:
    print -1
    break
  else:
    a[j]=0
    j = nj

Submission status: Accepted

Solution code:
def getinputdata():

    # 配列初期化
    array_result = []
    
    data = input()
    
    array_result.append(data.split(" "))

    flg = 1

    try:

        while flg:

            data = input()

            if(data != ""):
                
                array_result.append(data.split(" "))

            else:

                flg = 0
    finally:


        return array_result

arr_data = getinputdata()

n = int(arr_data[0][0])

arr=[int(arr_data[x][0]) for x in range(1,1+n)]

lamp=arr[0]

cnt=1
chkflg=False
for i in range(n):
    
    if lamp!=2:
        
        lamp=arr[lamp-1]
        cnt+=1
        
    else:
        
        chkflg=True
        break
        
print(cnt if chkflg else -1)

Submission status: Accepted

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

Submission status: Accepted

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

from collections import defaultdict
d = defaultdict(bool)
ans = 1
t = a[0]

for _ in range(n):
  if t==2:
    break
  else:
    if d[t]:
      ans = -1
      break
    else:
      d[t] = True
      t = a[t-1]
      ans += 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())

a=[0]*n
b=[1]*n

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

now=1

for i in range(n):
    if now==2:
        print(i)
        break
    elif b[now-1]==1:
        b[now-1]=0
        now=a[now-1]
    else:
        print(-1)
        break

Submission status: Accepted

Solution code:
N = int(input())
alist = []
for _ in range(N):
    alist.append(int(input()))
i = 1
for n in range(N):
    i = alist[i - 1]
    if i == 2:
        print(n + 1)
        break
else:
    print(-1)

Submission status: Accepted

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

while True:

    if current == 2:
        break
    if cnt > n:
        cnt = -1
        break
    current = a[current-1]
    cnt += 1

print(cnt)

Submission status: Accepted

Solution code:
N=int(input())
s=[int(input()) for i in range(N)]
p=s[0]
if p==2:
    print(1)
    exit()
for i in range(N):
    q=s[p-1]
    if q==2:
        print(i+2)
        exit()
    p=q
print(-1)

Submission status: Accepted

Solution code:
import sys

n = int(input())

numlist = []

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

index = 0
count = 1
while numlist[index] != 2:
  if numlist[index] == -1:
    print(-1)
    sys.exit()

  numlist[index], index = -1, numlist[index] - 1
  count += 1

print(count)

Submission status: Accepted

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

Submission status: Accepted

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

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

print(Ans)

Submission status: Accepted

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

N = int(input())
aN = [int(input()) for i in range(N)]

# 現在位置を保持する変数を使う
now = 1
for i in range(N):
    now = aN[now-1]
    if now == 2:
        print(i + 1)
        exit()
print(-1)

Submission status: Accepted

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

b = []
count = 0
i = 0

while count < N:
    b.append(A[i])
    i = A[i] - 1
    count += 1

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

Submission status: Accepted

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

pointer = input_list[0]
count = 1
index = 0

while True:
    if pointer == 2:
        print(count)
        break
    if index == 10**5 + 1:
        print(-1)
        break
    pointer = input_list[pointer-1]
    count += 1
    index += 1

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for i in range(N)]
flag = 0
res = -1

for i in range(N):
    flag = a[flag] -1
    if flag == 1:
        res = i + 1
        break
    
print(res)

Submission status: Accepted

Solution code:
def solve(N,a):
  visited = [False]*N
  h = 0
  cnt = 0
  while True:
    if visited[h]:
      return -1
    visited[h] = True
    if h == 1:
      return cnt
    cnt += 1
    h = a[h]

N=int(raw_input())
a=[None]*N
for i in xrange(N):
  a[i] = int(raw_input())-1
print solve(N,a)

Submission status: Accepted

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

i = 0
c = 1
while(1):
    if a[i]-1 == 1:
        print(c)
        break
    i = a[i]-1
    c += 1
    if c >= N or a[i]-1 == 0:
        print("-1")
        break

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
a = {i+1:int(input()) for i in range(n)}
nexti = 1
for i in range(n):
    if a[nexti] == 2:
        print(i+1)
        exit()
    nexti = a[nexti]
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = []
visited = []
place = 1
for i in range(N):
    a.append(int(input()))
for i in range(N):
    visited.append(place)
    place = a[place - 1]
if 2 in visited:
    print(visited.index(2))
else:
    print(-1)

Submission status: Accepted

Solution code:
import numpy
import re
import math

def main():
	"""
	テストコード実行
	:return:
	"""
	n = int(input())
	a = list(map(int, [int(input()) - 1 for i in range(n)]))
	cur = 0
	for i in range(10**5):
		cur = a[cur]
		if cur == 1:
			print(i + 1)
			exit()
	print("-1")

if __name__ == '__main__':
	main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) - 1 for _ in [0]*N]
cur = 0
cnt = -1
for i in range(N):
    cur = a[cur]
    if cur == 1:
        cnt = i + 1
        break
print(cnt)

Submission status: Accepted

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

if a[0] == 2:
    print(1)
else:
    count = 0
    i = a[0]
    flag = False
    for _ in range(n):
        count += 1
        if a[i-1] == 2:
            flag = True
            break
        i = a[i-1]
    if flag:
        print(count+1)
    else:
        print(-1)

Submission status: Accepted

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

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

button = 1
count = 0

aru = False
for i in range(N):
    button = a[button-1]
    count = count + 1
    if button == 2:
        aru = True
        break

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

Submission status: Accepted

Solution code:
N=int(input())
hairetsu=[]
count=0
pos=0

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

while count<=100001:
    pos=hairetsu[pos]-1
    count+=1
    if pos==1:
        print(count)
        exit()
print(-1)

Submission status: Accepted

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

b=0
c=0
count=0
while b!=1 and count!=len(a):
    b=a[b]-1
    count+=1
    #print(b)
if count==len(a): print('-1')
else: print(count)

Submission status: Accepted

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

used=[False for x in range(N)]
cnt=0
used[0]=True

ans=0
while True:
  cnt=A[cnt]-1
  ans+=1
  if used[cnt]:
    print(-1)
    break
  else:
    used[cnt]=True
    
  if cnt==1:
    print(ans)
    break

Submission status: Accepted

Solution code:
n = int(input())
a = [0] + [int(input()) for _ in range(n)]
s, i, ans = set([1]), a[1], 1
while(i != 2):
    if(not a[i] in s):
        s.add(a[i])
        i = a[i]
        ans += 1
    else:
        ans = -1
        break
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(input())for i in range(n)]
vis=[0]*n
i=0
cnt=0
while True:
    next=a[i]
    cnt+=1
    if vis[next-1]==1:#一度来たことがある点であればbreak
        print(-1)
        exit()
    vis[next-1]=1#一度光った点は記録
    if next==2:
        break
    i=next-1
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(input())for i in range(n)]
vis=[0]*n
i=0
cnt=0
while True:
    next=a[i]
    cnt+=1
    if vis[next-1]==1:
        print(-1)
        exit()
    vis[next-1]=1
    if next==2:
        break
    i=next-1
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
rec = {}
for i in range(n):
    a = int(input())
    rec[i + 1] = a

i = 1
rec2 = [1]
num = 0
while i != 2 and num < n:
    i = rec[i]
    num += 1

if num == n:
    print(-1)
else:
    print(num)

Submission status: Accepted

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

visited = [False] * (n + 1)
b = 1
cnt = 0
while b != 2:
    cnt += 1
    if visited[b]:
        print(-1)
        exit()
    else:
        visited[b] = True
        b = a[b - 1]
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for i in range(N)]
ans = 0
turn = 1
while True:
    if a[turn-1] == 2:
        ans += 1
        break
    if a[turn-1] == 0:
        ans = -1
        break
    next_turn = a[turn-1]
    a[turn-1] = 0
    ans += 1
    turn = next_turn

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
button = [int(input()) for _ in range(N)]
flag = [0] * N
current = 0
count = 0
while 1:
    if current == 1:
        break
    if flag[current] != 0:
        count = -1
        break
    else:
        flag[current] = button[current]
        current = flag[current] - 1
        count += 1
print(count)

Submission status: Accepted

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

for i in range(n):
    a = int(input())
    b[i+1] = b.get(i+1, 0) + a

key, t = b.get(1, 0), 1
key_set = {1}
while key != 0:
    if key in key_set:
        print(-1)
        break

    if key == 2:
        print(t)
        break

    key_set.add(key)
    key = b.get(key, 0)
    t += 1

else:
    print(-1)

Submission status: Accepted

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

p = 0
for k in range(N):
    if p == 1:
        print(k)
        exit()
    else:
        p = A[p]
print(-1)

Submission status: Accepted

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

button_history = [1]
current_button = 1
num_manipulation = -1

for i in range(1, N + 1):
    current_button = a_list[current_button - 1]
    if current_button == 2:
        num_manipulation = i
        break

print(num_manipulation)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,now,c=int(input()),0,-1
a=[int(input())-1 for i in range(n)]
for i in range(n):
    now=a[now]
    if now==1:
        c=i+1
        break
print(c)

Submission status: Accepted

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

count = 0
now = 0

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

if count == n+2:
    print(-1)
else:
    print(count)

Submission status: Accepted

Solution code:
def game():
    N = int(input())

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

    A_stopped = [False for i in range(N+1)]

    b = 1
    count = 0
    while(True):
        A_stopped[b] = True
        b = A[b]
        count += 1
        #print("{} Now_point: {}".format(count,b))
        if b==2:
            print(count)
            return 0
        elif A_stopped[b]:
            print("-1")
            return -1
            
game()

Submission status: Accepted

Solution code:
N = int(input())
temp_dict ={ i+1 : int(input()) for i, j in enumerate(range(N))}
reference_value = 1
for i in range(N):
    reference_value = temp_dict[reference_value]
    if reference_value == 2:
        print(i+1)
        break
    else:
        pass

if reference_value !=2:
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A_list = [0]
for i in range(N):
    A_list.append(int(input()))
A_flag = [False] * len(A_list)

idx = 1
count = 1
while True:
    if A_list[idx] == 2:
        print(count)
        break
    if A_flag[idx] is True:
        print(-1)
        break
    A_flag[idx] = True
    idx = A_list[idx]
    count += 1