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())
lamp = [int(input()) for i in range(n)]
cnt = 0
select = lamp[0]
while True:
  if cnt>n:
    print(-1)
    break;
  elif select == 2:
    cnt += 1
    print(cnt)
    break;
  else:
    select = lamp[select-1]
    cnt += 1

Submission status: Accepted

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

Submission status: Accepted

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

while cnt <= N:
  lgt = a[i]
  cnt += 1
  if lgt == 2:
    print(cnt)
    break
  i = lgt - 1
else:
  print(-1)

Submission status: Accepted

Solution code:
N = int(input())

L = []
for i in range(1,N+1):
  L.append((i,int(input())))

o = L[0][1]
cnt = 1
while o != 2:
  o = L[o-1][1]
  cnt += 1
  if cnt > N:
    print(-1)
    exit()
    
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
button = []
for i in range(n):
  button.append(int(input()))
times = 0
next_button = 1
while times < n:
  times += 1
  next_button = button[next_button-1]
  if next_button == 2:
    print(times)
    exit()
print(-1)

Submission status: Accepted

Solution code:
n = int(input().strip())
a = [int(input().strip()) for _ in range(n)]
visited = [False] * n
visited[0] = True
now = 0
ans = 0
while True:
    now = a[now] - 1
    ans += 1
    if now == 1:
        print(ans)
        exit()
    elif visited[now]:
        print(-1)
        exit()
    visited[now] = True

Submission status: Accepted

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

cnt = [0]*(N+1)
now = 1
c = 0
while True:
    # 今ついてる箇所の確認
    cnt[now] += 1
    if cnt[now] > 1:
        print(-1)
        break

    # 次にアクセス
    now = a[now]
    c += 1
    if now == 2:
        print(c)
        break

Submission status: Accepted

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

x = 0
cnt = 0
for i in a:
    if a[x] == -1:
        print(-1)
        exit()
    else:
        t = x
        x,a[t] = a[x],-1
        cnt += 1
        if x == 1:
            print(cnt)
            exit()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N = int(readline())
    A = [0]
    for _ in range(N):
        A.append(int(readline()))
    used = [False]*(N+1)
    now = 1
    count = 0
    while not used[now]:
        used[now] = True
        now = A[now]
        count += 1
        if now == 2:
            print(count)
            break
    else:
        print(-1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest

sys.setrecursionlimit(10**6)

def rec(n, a, seen):
	if seen[n-1]:
		return -1
	if a[n-1] == 2:
		return seen.count(True) + 1
	seen[n-1] = True
	return rec(a[n-1], a, seen)

def resolve():
	n = int(input())
	a = []
	seen = [False]*n
	for _ in range(n):
		a.append(int(input()))
	print(rec(1, a, seen))
resolve()

Submission status: Accepted

Solution code:
import sys
N = int(sys.stdin.readline())
a = list(int(sys.stdin.readline()) for i in range(N))
count = 0
index = 1
while count <= N:
    lump = a[index - 1]
    count += 1
    if lump == 2:
        print(count)
        exit()
    else:
        index = lump
print(-1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
a=[]
for i in range(n):
  b=int(input())
  a.append(b)
roop=[False]*n
bottun=1
count=0
while bottun!=2:
  if roop[bottun-1]:
    count=-1
    break
  count+=1
  roop[bottun-1]=True
  bottun=a[bottun-1]
print(count)

Submission status: Accepted

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

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

print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

d = defaultdict(int)
for i, e in enumerate(a, 1):
    d[i] = e

count = 1
tmp = d[1]
if tmp == 2:
    print(1)
    exit()

while count <= N:
    v = d[tmp]
    count += 1
    if v == 2:
        print(count)
        exit()
    tmp = v
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
List = [int(input()) for i in range(N)]
count = 1
i = 0
while True:
  if List[i] == 2 or count == N:
    break
  else:
    count += 1
    i = List[i] -1

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

Submission status: Accepted

Solution code:
import sys

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


def resolve():
    n = int(input())
    A = list(int(input()) for _ in range(n))

    i = 1
    res = 0
    for _ in range(n):
        i = A[i - 1]
        res += 1
        if i == 2:
            break
    else:
        print(-1)
        exit()

    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys
N = int(input())
a = [int(input()) for i in range(N)]
q = 1
cnt = 0
li = []
for i in range(100001):
    q = a[q-1]
    cnt += 1
    if q == 2:
        print(cnt)
        sys.exit()
print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(input()) for _ in range(n)]
ans=-1
b=a[0]
if b==2:
    print(1)
else:
    for i in range(n):
        b=a[b-1]
        # print(f"b={b}")
        if b==2:
            ans=i+2
            break
    print(ans)

Submission status: Accepted

Solution code:
import collections
import heapq


class Dijkstra():
    def __init__(self):
        self.e = collections.defaultdict(list)

    def add(self, u, v, d, directed=False):
        """
        #0-indexedでなくてもよいことに注意
        #u = from, v = to, d = cost
        #directed = Trueなら、有向グラフである
        """
        if directed is False:
            self.e[u].append([v, d])
            self.e[v].append([u, d])
        else:
            self.e[u].append([v, d])

    def delete(self, u, v):
        self.e[u] = [_ for _ in self.e[u] if _[0] != v]
        self.e[v] = [_ for _ in self.e[v] if _[0] != u]

    def Dijkstra_search(self, s):
        """
        #0-indexedでなくてもよいことに注意
        #:param s: 始点
        #:return: 始点から各点までの最短経路と最短経路を求めるのに必要なprev
        """
        d = collections.defaultdict(lambda: float('inf'))
        prev = collections.defaultdict(lambda: None)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for uv, ud in self.e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv] > vd:
                    d[uv] = vd
                    prev[uv] = u
                    heapq.heappush(q, (vd, uv))

        return d, prev

    def getDijkstraShortestPath(self, start, goal):
        _, prev = self.Dijkstra_search(start)
        shortestPath = []
        node = goal
        while node is not None:
            shortestPath.append(node)
            node = prev[node]
        return shortestPath[::-1]


N = int(input())
graph = Dijkstra()
for i in range(N):
    a = int(input())
    graph.add(i+1, a, 1, True)

ans = graph.Dijkstra_search(1)[0][2]
if ans == float('inf'):
    print(-1)
    quit()
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque, Counter, defaultdict
from itertools import accumulate  # 累積和
from bisect import bisect_left, bisect
from heapq import heappop, heappush  # 優先度付きキュー
from fractions import gcd
from math import ceil, floor, sqrt
from copy import deepcopy

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

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

print(-1)

Submission status: Accepted

Solution code:
N = int(input())
S = [int(input()) for i in range(N)]
count=1
i=0
while True:
  if S[i]==2 or count==N:
    break
  else:
    count+=1
    i=S[i]-1
if count==N: print(-1)
else: print(count)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

ai = 1
count = 1
while check[ai-1]:
  if A[ai-1] == 2:
    print(count)
    exit()
  check[ai-1] = False
  ai = A[ai-1]
  count += 1
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a_list = list()
for _ in range(n):
    a_list.append(int(input()))
light_button = 1
target_light_button = 2
for i in range(n):
    light_button_index = light_button - 1
    light_button = a_list[light_button_index]
    if light_button == target_light_button:
        print(i + 1)
        exit(0)
print(-1)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

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

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
n = int(input())
a = [int(input()) for i in range(n)]
v = [0 for i in range(n)]
ans = 0
x = 0
while x != 1:
    if v[x] == 1:
        ans = -1
        break
    v[x] = 1
    x = a[x] - 1
    ans += 1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def resolve():
    N = int(input())
    A = [int(input()) for i in range(N)]
    idx = 0
    target = 1
    cnt = 1
    passed = [False]*N
    while True:
        if idx >= N:
            print(-1)
            return
        if A[idx]-1 == target:
            print(cnt)
            return
        if passed[A[idx]-1]:
            print(-1)
            return
        passed[idx] = True
        idx = A[idx]-1
        cnt += 1



if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
n = int(input())
al = [int(input())-1 for _ in range(n)]
used = [False] *n
s = 0
res = 0
used[s] = True
while s != 1:
    s = al[s]
    if used[s]:
        print(-1)
        exit()
    used[s] = True
    res += 1
print(res)

Submission status: Accepted

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

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

Submission status: Accepted

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

next_i = 0
cnt = 0
ans = -1
for i in range(N):
    if next_i == 1:
        ans = cnt
        break
    next_i = array[next_i]-1
    cnt += 1
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
# =map(int,input().split())
import sys
n=int(input())
a=[]
for i in range(n):
    x=int(input())
    a.append(x)
key=1
ans=0
for _ in range(n):
    ans+=1
    if a[key-1]==2:
        print(ans)
        sys.exit()
    else:
        key=a[key-1]
print(-1)

Submission status: Accepted

Solution code:
n = int(input())
a = [0]*n
for i in range(n):
    a[i] = int(input())
b = 1
count = 0
sw = 0
for i in range(n):
    b = a[b-1]
    count += 1
    if b == 2:
        sw = 1
        break
    elif count>=10**5:
        break
if sw == 1:
    print(count)
else:
    print(-1)

Submission status: Accepted

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

"""
    条件
        - はじめ、ボタン1が光っている
        - ボタン2が光っている状態で終了したい
        - そのようなことは可能か？可能ならボタンを押す最低回数を、不可能なら-1を出力せよ。
"""

ans = -1
cnt = 0
pos = 0
for _ in range(N): # N回ボタンを押す
    cnt += 1
    pos = aa[pos] - 1
    if pos == 1:
        ans = cnt
        break

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
al = [int(input())-1 for _ in range(n)]
used = [False]*n
s = 0
res = 0
used[s] = True
while s!=1:
    s = al[s]
    if used[s]:
        print(-1)
        exit()
    used[s] = True
    res += 1
print(res)

Submission status: Accepted

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

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

Submission status: Accepted

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

a = [0 for i in range(N+1)]

#aの入力
for i in range(1,N+1):
    a[i]=input()
    a[i]=int(a[i])

#ボタン処理
#ボタン1からスタート
count=0
num=1
while True:
    #2のボタンに到達したか？
    if num==2:
        #最終出力、パターン1
        print(count)
        break
    else:
        if a[num]==0:
            #ゼロならループに入るので、whileを外れる
            #最終出力、パターン1
            print(-1)
            break
        else:
            #カウントを1増
            count+=1
            #numを一度退避
            temp=num
            #numを次のボタンへ
            num=a[num]
            #既に使った印として、今使ったボタンの中身を0に
            a[temp]=0

Submission status: Accepted

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

Submission status: Accepted

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

def main():
    N = int(readline())
    A = [int(readline()) - 1 for _ in range(N)]
    ans = 0
    pre = 0
    visited = set([0])
    while ans <= N:
        pre = A[pre]
        if pre in visited:
            print(-1)
            return
        visited.add(pre)
        ans += 1
        if pre == 1:
            print(ans)
            return
    
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

light = 1
for i in range(N):
    if light == 2:
        ans = i
        break
    else:
        light = botton[light - 1]

if light == 2:
    print(ans)
else:
    print(-1)

Submission status: Accepted

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

hst = [0] * n
btn = 0
cnt = 0

while hst[btn] != 1:
    hst[btn] = 1
    btn = a[btn]

    cnt += 1
    if btn == 1:
        print(cnt)
        exit()

print(-1)

Submission status: Accepted

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

# if not 1 in a:
#     print(-1)

# hst = []
btn = 0
cnt = 0

while cnt <= 10**7:
    # hst.append(btn)
    btn = a[btn]
    cnt += 1
    if btn == 1:
        print(cnt)
        exit()

print(-1)

Submission status: Accepted

Solution code:
n=int(input())
ans=""
cnt=0
lst=list(int(input()) for _ in range(n))
i=1
for _ in range(n):
	cnt += 1
	if lst[i-1]==2:
		break
	else: i=lst[i-1]
else:cnt=-1
print(cnt)

Submission status: Accepted

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

count = 0
for i in range(n+10):
    count += 1
    p = a[p]
    if p == 1:
        print(count)
        break
else:
    print(-1)

Submission status: Accepted

Solution code:
n = int(input())
x = [int(input()) for i in range(n)]
c=0
a=1
while True:
	if c==n+1:
		print('-1')
		break
	a=x[a-1]
	c+=1
	if a==2:
		print(c)
		break

Submission status: Accepted

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

cnt = 0
cur = 1

if a[0] == 2:
    print(1)
    exit()

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

print(-1)

Submission status: Accepted

Solution code:
N = int(input())

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

b = a[0]
li = [0]
c = 1

while b != 2:
    li += [b-1]
    b = a[b-1]
    c += 1
    if c > N:
        print(-1)
        break
else:
    print(c)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
q = []
a=[]
for i in range(n):
    a.append(int(input())-1)
q.append(a[0])
cnt=0

while q:
    cnt+=1
    i = q.pop()
    q.append(a[i])
    if i==1:
        print(cnt)
        exit()
    if cnt>10**5:
        print(-1)
        exit()
print(-1)

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
q = deque()
a=[]
for i in range(n):
    a.append(int(input())-1)
q.append(a[0])
cnt=0

while q:
    cnt+=1
    i = q.pop()
    q.append(a[i])
    if i==1:
        print(cnt)
        exit()
    if cnt>10**5:
        print(-1)
        exit()
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
count = 0
i = 1
x = 0
osita = [0]*(N+1)
for b in range(N+1):
    osita[b] = i
    i = a[i-1]
    
if 2 in osita:
    print(osita.index(2))
else:
    print(-1)

Submission status: Accepted

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
ne = 1
cnt = 0
while True:
    cnt += 1
    ne = a[ne-1]
    if ne == 2:
        print(cnt)
        break
    if N <= cnt:
        print(-1)
        break

Submission status: Accepted

Solution code:
n = int(input())

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

ans = 0
now = 0
while 1:
    flag[now] = False
    now = a[now] - 1
    ans += 1
    if flag[now] == False:
        print(-1)
        exit()
    elif now == 1:
        break
print(ans)

Submission status: Accepted

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

flag = False
ind = 1
for cnt in range(n):
  ind = a[ind-1]

  if ind == 2:
    flag = True
    break

print(cnt+1 if flag else -1)

Submission status: Accepted

Solution code:
N=int(input())
A = []
for i in range(N):
  Ai=int(input())
  A.append(Ai)
on = 1 #現実世界での番号
for i in range(N):
  on = A[on-1] #次のボタンを知るために、配列を参照する
  if on == 2:
    print(i+1)
    break
if on != 2:
  print(-1)

Submission status: Accepted

Solution code:
from collections import defaultdict

N = int(input())
a = [int(input()) for _ in range(N)]
seen_list = defaultdict(int)
n = 1
ans = 0
while True:
    if seen_list[n] == 1:
        print(-1)
        exit()
    else:
        if n == 2:
            print(ans)
            exit()
        else:
            seen_list[n] = 1
            n = a[n - 1]
            ans += 1

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for i in range(N)]
B = 0
C = 1
for j in range(N):
  if A[B] == 2:
    print(C)
    break
  elif j == N-1:
    print('-1')
  else:
    B = A[B]-1
    C += 1

Submission status: Accepted

Solution code:
N = int(input())
A = [0]
for _ in range(N):
    A.append(int(input()))
S = set()
i = 1
cnt = 0
while i != 2 and not i in S:
    S.add(i)
    i = A[i]
    cnt += 1
if i == 2:
    print(cnt)
else:
    print(-1)

Submission status: Accepted

Solution code:
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

import sys
sys.setrecursionlimit(1000000)

n = ii()
s = set()
l = []
cnt = 0
def solve(index,cnt):
    if l[index] == 2:
        print(cnt+1)
        exit()
    elif l[index] in s:
        print(-1)
        exit()
    else:
        s.add(l[index])
        solve(l[index]-1,cnt+1)
    return 0

for i in range(n):
    num = ii()
    l.append(num)

solve(0,cnt)

Submission status: Accepted

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

cur = 0
visited = set()
count = 0
while cur != 1:
    if cur in visited:
        print(-1)
        break
    visited.add(cur)
    cur = a[cur] - 1
    count += 1

else:
    print(count)

Submission status: Accepted

Solution code:
b=True

n,*a=map(int,open(0).read().split())

p=0

for i in range(n):
    p=a[p]-1
    if p==1:
        print(i+1)
        b=False
        break
    
if b:
    print(-1)

Submission status: Accepted

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

temp = 1
count = 0
while temp != 2 and count <= 100001:
	temp = a[temp - 1]
	count += 1

if count > 100000:
	print(-1)
else:
	print(count)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def myAnswer(N:int,A:list) ->int:
   if((2 in A) == False):return -1
   graph = {}
   for n,a in enumerate(A):
      graph[n] = a - 1
   i = 0
   counter = 0
   while True:
      if(graph[i] == "-"):
         return -1
      if(graph[i] == 1):
         counter += 1
         break
      tmp = graph[i]
      graph[i] = "-"
      i = tmp
      counter += 1
   return counter




def modelAnswer():
   tmp=1
def main():
   N = int(input())
   A = [int(input()) for _ in range(N)]
   print(myAnswer(N,A[:]))
if __name__ == '__main__':
   main()

Submission status: Accepted

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

cnt = 0
prev = 1
while True:
  nxt = A[prev]
  cnt += 1
  
  if nxt == 2:
    break
    
  USED[prev] = True
  if USED[nxt]:
    cnt = -1
    break
    
  prev = nxt
    
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
A = [int(input()) - 1 for _ in range(n)]
pushed = [False] * n
q = [0]
ans = 0
while q:
    b = q.pop()
    ans += 1
    pushed[b] = True
    if pushed[A[b]]:
        ans = -1
        break
    if A[b] == 1:
        break
    q.append(A[b])
print(ans)

Submission status: Accepted

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

# print(A)
cur = 1
Npush = 0
# History = []
# while 1:
#     History.append(cur)
#     cur = A[cur-1]
#     Npush+=1
#     if cur == 2:
#         break
#     elif cur in History:
#         Npush=-1
#         break
for i in range(N+1):
    cur = A[cur-1]
    Npush += 1
    if cur == 2:
        break
    # print(cur)
if cur==2:
    print(Npush)
else:
    print(-1)

Submission status: Accepted

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

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

Submission status: Accepted

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

F = [0 for i in range(N+1)]
#F[1]=1

s = 1


for i in range(N*2):
  s = A[s-1]
  F[s]+=1
  if F[2]==1:
    print(i+1)
    exit()
  if F[s]>=2:
    print(-1)
    exit()

Submission status: Accepted

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

cnt = 0
idx = 0
flg = False
for _ in range(n):
    k = a[idx]
    idx = k-1
    cnt += 1
    if idx == 1:
        flg = True
        break
        
if flg:
    print(cnt)
else:
    print(-1)

Submission status: Accepted

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

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

now=1
cnt=0
arrive=False
for i in range(N):
    now=R[now]
    cnt+=1
    if now==2:
        arrive=True
        break

if arrive:
    print(cnt)
else:
    print('-1')

Submission status: Accepted

Solution code:
n = int(input())

a_i_list = []

push_i = 1
GOAL_i = 2

is_loop = False
pushed_i_list = []

push_counter = 0

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

while (True):
  push_counter += 1

  # pushed_i_list.append(push_i)
  current_index = push_i - 1
  push_i = a_i_list[push_i - 1]
  
  # 一度使用したボタンは数値を0にする
  a_i_list[current_index] = 0

  if a_i_list[push_i - 1] == 0:
    push_counter = -1
    break
  
  if push_i == GOAL_i:
    break


print(push_counter)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N=int(input())
L=[]
for i in range(N):
	L.append(int(input()))
count=0
ans=0
i=0
while(1):
	count+=1
	if count==N+100:
		print(-1)
		exit()
	i=L[i]-1
	ans+=1
	if i==1:
		print(ans)
		exit()

Submission status: Accepted

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

Submission status: Accepted

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

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