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: Time Limit Exceeded

Solution code:
N = int(input())
btn = [int(input())-1 for _ in range(N)]
i = 0
li = [0]

while True:
    k = btn[i]
    #print(k, li)
    if k in li:
        print('-1')
        break
    else:
        if k != 1:
            li.append(k)
        else:
            print(len(li))
            break
    i = k

Submission status: Time Limit Exceeded

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

b = 1
n = 0
move = []

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

Submission status: Time Limit Exceeded

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

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

import sys
input = sys.stdin.readline

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Submission status: Time Limit Exceeded

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

fp = [a[0]]
now = a[0]
cnt = 0

while now != 2:
    cnt += 1
    now = a[now-1]
    if now in fp:
        print(-1)
        exit()
    fp.append(now)

if now == 2:
    cnt += 1

print(cnt)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

#n = 5
#a = [3,3,4,2,4]

a.insert(0,0)

i = 1
pushed = [1]
ans = 0
while(1):
  ans += 1
  if a[i] == 2:
    break
  if a[i] in pushed:
    ans = -1
    break
  else:
    pushed.append(a[i])
    i = a[i]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
a = [int(input()) for _ in range(N) ]
hist = [1]
bottun = 0
i = 0

while True:
    # print(hist)
    bottun = a[hist[i]-1]
    # print(bottun)
    for j in hist:
        if bottun == j:
            print(-1)
            # print("hoge")
            exit()
    
    if bottun == 2:
        print(len(hist))
        exit()
    
    hist.append(bottun)
    i += 1

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
dic={}
for i in range(n):
    dic[i+1]=int(input())
ans=[1]
while True:
    if dic[ans[-1]]==2:
        print(len(ans))
        break
    if dic[ans[-1]] in ans:
        print(-1)
        break
    ans.append(dic[ans[-1]])

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

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

b = []

num=a[0]

count=1
if a[0]==2:
    print(1)
else:
    while(1):
        if num == 2:
            print(count)
            exit()
        if num not in b:
            b.append(num)
            num = a[num-1]
            count+=1
        else:
            print('-1')
            exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
N = int(input())
a = [int(input()) for i in range(N)]
d = [0]
b = 0
c = 0
while True:
    if b == 1:
        print(c)
        sys.exit()
    c += 1
    b = a[b] - 1
    if b in d:
        print('-1')
        sys.exit()
    d.append(b)

Submission status: Time Limit Exceeded

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

ans = 0
visited = set([0])
next_visit_idx = 0
while True:
  next_visit_idx = a[next_visit_idx] -1
  ans += 1
  if next_visit_idx == 1:
    print(ans)
    break
  if next_visit_idx in visited:
    print(-1)
    break

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ns = [int(input()) for _ in range(n)]
i = 0
cnt = 0
pushed = [0]
flg = False
while(True):
    cnt += 1
    i = ns[i] - 1
    if i in pushed:
        break
    pushed.append(i)
    if i == 1:
        flg = True
        break
if flg:
    print(cnt)
else:
    print(-1)

Submission status: Time Limit Exceeded

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

    move = []
    i = 0
    ans = 1
    while As[i] != 2:
        if As[i] not in move:
            move.append(As[i])
            ans += 1
            i = As[i]-1
        else:
            ans = -1
            break
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
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()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()

a = [INT() for _ in range(N)]
tmp = [0]*(N+1)
tmp2 = a[0]
cnt = 0
while 1:
	if tmp2 == 1:
		print(-1)
		break
	elif tmp2 == 2:
		print(cnt+1)
		break
	tmp[tmp2] = 1
	tmp2 = a[tmp2-1]
	cnt += 1

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
 
s = []
cnt = 0
n = 1
f = False
while cnt <= N:
  s.append(n)
  cnt += 1
  n = A[n - 1]
  if n == 2:
    f = True
    break
  elif n in s:
    break
print(cnt if f else -1)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
 
s = []
cnt = 0
n = 1
f = False
while cnt <= N:
  s.append(n)
  cnt += 1
  n = A[n - 1]
  if n == 2:
    f = True
    break
  elif s.count(n) != 0:
    break
print(cnt if f else -1)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
 
s = []
cnt = 0
n = 1
f = False
while True:
  s.append(n)
  cnt += 1
  n = A[n - 1]
  if n == 2:
    f = True
    break
  elif s.count(n) != 0:
    break
print(cnt if f else -1)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
s = []
cnt = 0
n = 1
f = False
while True:
  cnt += 1
  s.append(n)
  if A[n - 1] == 2:
    f = True
    break
  elif s.count(A[n - 1]) == 1:
    break
  n = A[n - 1]
print(cnt if f else -1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [0]+[int(input()) for _ in [0]*n]
used = [False, True]+[False]*(n-1)
ans = 0
now = 1
while now!=2:
    b = a[now]
    if not used[b]:
        now = a[now]
        ans += 1
    else:
        print(-1)
        break
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    N = int(_in[0])  # type:int
    a_arr = [None]
    for i in range(N):
        _ = int(_in[i+1])  # type:int
        a_arr.append(_)
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    memo = []
    now = 1
    cnt = 0
    while True:
        cnt += 1
        _ = a_arr[now]
        if _ in memo or cnt>N:
            cnt = -1
            break
        elif _ == 2:
            break
        else:
            memo.append(_)
            now = _
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    print(cnt)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    N = int(_in[0])  # type:int
    a_arr = [None]
    for i in range(N):
        _ = int(_in[i+1])  # type:int
        a_arr.append(_)
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    memo = []
    now = 1
    cnt = 0
    while True:
        cnt += 1
        _ = a_arr[now]
        if _ in memo:
            cnt = -1
            break
        elif _ == 2:
            break
        else:
            memo.append(_)
            now = _
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

n = int(input())
a = [0] + [int(sys.stdin.readline()) for _ in range(n)]

pushed = deque([1])
button = 1

for _ in range(n):
    if a[button] in pushed:
        print(-1)
        break
    pushed.append(a[button])
    button = a[button]
    if button == 2:
        print(len(pushed) - 1)
        break

Submission status: Time Limit Exceeded

Solution code:
import sys

n = int(input())
a = [0] + [int(sys.stdin.readline()) for _ in range(n)]

pushed = [1]
button = 1

for _ in range(n):
    if a[button] in pushed:
        print(-1)
        break
    pushed.append(a[button])
    button = a[button]
    if button == 2:
        print(len(pushed) - 1)
        break

Submission status: Time Limit Exceeded

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

pushed = [1]
button = 1

while button != 2:
    if a[button] in pushed:
        print(-1)
        break
    pushed.append(a[button])
    button = a[button]
else:
    print(len(pushed) - 1)

Submission status: Time Limit Exceeded

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

j=0
ans=0
count=[0]*N
while j!=1:
    ans+=1
    j=A[j]-1
    count[ans]=j
    if count.count(j)>=2:
        ans=-1
        break

print(ans)

Submission status: Time Limit Exceeded

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

j=0
ans=0
count=[0]*N
while j!=1:
    ans+=1
    j=A[j]-1
    count[ans]=j
    if count.count(j)==2:
        ans=-1
        break

print(ans)

Submission status: Time Limit Exceeded

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

j=0
ans=0
count=[]
while j!=1:
    j=A[j]-1
    count.append(j)
    if count.count(j)==2:
        ans=-1
        break
    ans+=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n=int(input())
A = [0]*n
B = [int(input())-1 for i in range(n)]
C = [0]

def fun(k):
    if B[k] in C:
        print(-1)
        sys.exit()                      
    else:
        C.append(B[k])
        if B[k] == 1:
            return False                                                    
        else:
            return B[k]
ans = 0
cnt = 0
for i in range(n):
    cnt = fun(cnt)
    ans +=1
    if cnt ==False:
        print(ans)
        sys.exit()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
i = 1
count = 0
btn = [1]
if 2 not in a:
  print(-1)
  exit()
while(1):
  i = a[i-1]
  count += 1
  if i in btn:
    print(-1)
    break
  if i == 2:
    print(count)
    break
  btn.append(i)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
i = 1
count = 0
btn = [1]
while(1):
  i = a[i-1]
  count += 1
  if i in btn:
    print(-1)
    break
  if i == 2:
    print(count)
    break
  btn.append(i)

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc065/tasks/abc065_b

def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))

N = INT()
a = []
for _ in range(N):
    a.append(INT() - 1)

light_idx = 0

ans = 0
while True:
    light_idx = a[light_idx]
    ans += 1

    if light_idx == 1:
        break

    if light_idx == 0:
        ans = -1
        break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=[]
for i in range(n):
  a.append(int(input()))
keep=1
count=0
lis=[]
for i in range(n):
  count+=1
  if keep in lis:
    print(-1)
    break
  lis.append(keep)
  keep=a[keep-1]
  if keep==2:
    print(count)
    break

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=[]
for i in range(n):
  a.append(int(input()))
keep=1
count=0
lis=[]
while keep!=2:
  count+=1
  if keep in lis:
    print(-1)
    break
  lis.append(keep)
  keep=a[keep-1]
  if keep==2:
    print(count)
    break

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=[]
for i in range(n):
  a.append(int(input()))
keep=1
count=0
lis=[]
while keep!=2:
  count+=1
  if keep in lis:
    print(-1)
    break
  lis.append(keep)
  keep=a[keep-1]
  if keep==2:
    print(count)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

i = 1
before_i = None
cnt = 0
while True:
    next_i = a[i]
    cnt += 1
    if next_i in [1, i, before_i]:
        print(-1)
        break
    elif next_i == 2:
        print(cnt)
        break

    before_i = i
    i = next_i

Submission status: Time Limit Exceeded

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

i = 1
before_i = None
cnt = 0
while True:
    next_i = a[i]
    cnt += 1
    if next_i in [1, i, before_i]:
        print(-1)
        break
    elif next_i == 2:
        print(cnt)
        break

    i = next_i

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
dic = {}
for i in range(1,N+1):
    dic[i] = int(input())
b = 1
lis = []
cnt = 0
while True:
    lis.append(b)
    b = dic[b]
    cnt += 1
    if b == 2:
        print(cnt)
        break
    elif b in lis:
        print(-1)
        break

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
num = 0
count = 0
a_list = []

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

if a_list.count(1) == 0:
    print(-1)
    exit()

while num != 1:
    num = a_list[num]
    count += 1

print(count)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
lamp = [int(input()) for i in range(n)]
lst = []
cnt = 0
select = lamp[0]
while True:
  if select in lst or cnt == n:
    print(-1)
    break;
  elif select == 2:
    cnt += 1
    print(cnt)
    break;
  else:
    lst.append(select)
    select = lamp[select-1]
    cnt += 1

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
lamp = [int(input()) for i in range(n)]
lst = []
cnt = 0
select = lamp[0]
while True:
  if select in lst:
    print(-1)
    break;
  elif select == 2:
    cnt += 1
    print(cnt)
    break;
  else:
    lst.append(select)
    select = lamp[select-1]
    cnt += 1

Submission status: Time Limit Exceeded

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()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
L = [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.append(a[i]-1)
        cnt += 1
        i = a[i]-1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
L = [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.append(a[i]-1)
        cnt += 1
        i = a[i]-1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
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)
        break
    if q in li:
        print(-1)
        break
    li.append(q)

Submission status: Time Limit Exceeded

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

memo = []
p = 1
ans = 0
while True:
  memo.append(p)
  p = a[p-1]
  ans += 1
  if p == 2:
    print(ans)
    break
  if p in memo:
    print(-1)
    break

Submission status: Time Limit Exceeded

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



if '__main__' == __name__:
    resolve()

Submission status: Time Limit Exceeded

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

hst = []
btn = 0
cnt = 0

while not btn in hst and cnt <= 10**5:
    hst.append(btn)
    btn = a[btn]
    cnt += 1
    if btn == 1:
        print(cnt)
        exit()

print(-1)

Submission status: Time Limit Exceeded

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

hst = []
btn = 0
cnt = 0

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

print(-1)

Submission status: Time Limit Exceeded

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]
    if b-1 in li:
        print(-1)
        break
    else:
        c += 1
else:
    print(c)

Submission status: Time Limit Exceeded

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

for i in range(n):
    y = a[y-1]
    x.append(y)
    if y == 2:
        break
    if x.count(y) == 2:
        print(-1)
        exit()

print(len(x)-1)

Submission status: Time Limit Exceeded

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

while y != 2:
    y = a[y-1]
    x.append(y)
    if x.count(y) == 2:
        print(-1)
        exit()

print(len(x)-1)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
count = 0
i = 1
osita = []
while 2 not in osita:
    osita.append(i)
    i = a[i-1]
    count += 1
    if count > len(a):
        print(-1)
        exit()
print(count-1)

Submission status: Time Limit Exceeded

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

flag = False
mem = []
ind = 0
while not flag:
  if a[ind] in mem:
    break

  if a[ind] == 2:
    flag = True
    break
    
  mem.append(a[ind])    
  ind = a[ind] - 1
  
print(len(mem)+1 if flag else -1)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
def myAnswer(N:int,A:list) ->int:
   if((2 in A) == False):return -1
   botton = A[0]
   keiro = [1]
   counter = 0
   while botton != 2:
      botton = A[botton - 1]
      if(botton in keiro):
         return -1
      keiro.append(botton)
      counter += 1
   return counter+1


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: Time Limit Exceeded

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
    
print(cnt)

Submission status: Time Limit Exceeded

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
    # print(cur)
print(Npush)

Submission status: Time Limit Exceeded

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)

  push_i = a_i_list[push_i-1]

  if push_i in pushed_i_list:
    push_counter = -1
    break
  
  if push_i == GOAL_i:
    break


print(push_counter)

Submission status: Time Limit Exceeded

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

s = [1]
while True:
  a = A[s[-1] - 1]
  if a in s:
    print(-1)
    break
  if a == 2:
    print(len(s))
    break
  s.append(a)

Submission status: Time Limit Exceeded

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

pos = 1
route = []
success = False
while 1:
    route.append(pos)
    pos = a[pos - 1]
    if pos == 2:
        print(len(route))
        break
        
    if pos in route:
        print(-1)
        break

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n=int(input())
blist=deque([int(input()) for a in range(n)])
vlist=deque([1])
while True:
    if 2 == vlist[-1]:
        print(len(vlist)-1)
        break
    a=blist[vlist[-1]-1]
    if a in deque([a for a in vlist]):
        print(-1)
        break
    else:
        vlist.append(a)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
blist=[int(input()) for a in range(n)]
vlist=[1]
while True:
    if 2 in vlist:
        print(len(vlist)-1)
        break
    vlist.append(blist[vlist[-1]-1])
    if vlist[-1] in vlist[0:-1]:
        print(-1)
        break

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

lightned = []
lightning = 0

while a[lightning] not in lightned:
    if a[lightning] == 1:
        break

    lightned.append(a[lightning])
    lightning = a[lightning]

print(len(lightned) + 1 if a[lightning] == 1 else -1)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    a = [0 for i in range(N)]
    for i in range(N):
        a[i] = int(input())
    d = [1]
    ans = 0
    for i in range(N):
        if a[d[i]-1] == 2:
            ans += 1
            break
        elif a[d[i]-1] in d or i == N - 1:
            ans = -1
            break
        else:
            d.append(a[d[i]-1])
            ans += 1
    print(ans)
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    a = [0 for i in range(N)]
    for i in range(N):
        a[i] = int(input())
    d = [1]
    ans = 0
    for i in range(N):
        if a[d[i]-1] == 2:
            ans += 1
            break
        elif a[d[i]-1] in d:
            ans = -1
            break
        else:
            d.append(a[d[i]-1])
            ans += 1
    print(ans)
main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from copy import deepcopy
sys.setrecursionlimit(10 ** 9)

n = int(input())
lista = [[] for i in range(n + 1)]
ans = float('inf')
for i in range(n):
    a = int(input())
    lista[i + 1].append(a)
def dfs(now, ignore):
    global ans
    if now == 2:
        ans = min(ans, len(ignore) - 1)
    for i in lista[now]:
        if i in ignore:
            continue
        nignore = deepcopy(ignore)
        nignore.append(i)
        dfs(i, nignore)
dfs(1, [1])
print(-1 if ans == float('inf') else ans)

Submission status: Time Limit Exceeded

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

now = 0
count = 0
while True:
    if now == 0 and count != 0:
        print(-1)
        break

    if now == 1:
        print(count)
        break

    now = A[now] - 1
    count += 1

Submission status: Time Limit Exceeded

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

now = 0
count = 0
while True:
    count += 1
    if A[now] == 1:
        print(-1)
        break

    if A[now] == 2:
        print(count)
        break

    now = A[now] - 1

Submission status: Time Limit Exceeded

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

cnt = 0
pos = 0

while True:
    if pos == 1:
        print(cnt)
    if cnt >= N:
        print(-1)

    pos = A[pos] - 1
    cnt += 1

Submission status: Time Limit Exceeded

Solution code:
def solve():
    a = [int(input()) for i in range(1, int(input()) + 1)]
    # ループしたら終わる
    l = []
    s = a[0]
    l.append(s)
    c = 1
    while(True):
        if s == 2:
            print(c)
            return True
        s = a[s - 1]
        if s in l:
            print(-1)
            return False
        l.append(s)
        c += 1
solve()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a_list = []
for i in range(n):
	a_list.append(int(input()))
r = -1
num = 1
nums = [1]
count = 0
while True:
	num = a_list[num-1]
	count += 1
	if num in nums:
		break
	if num == 2:
		r = count
		break
	if count == n:
		break
	nums.append(num)
print(r)