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: Runtime Error

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 math import factorial, sqrt, ceil, gcd
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: Runtime Error

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

p = 1
ans = 0
while True:
  tmp = p
  p = a[p-1]
  a[tmp] = 0
  ans += 1
  if p == 0:
    print(-1)
    break
  if p == 2:
    print(ans)
    break

Submission status: Runtime Error

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

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

Submission status: Runtime Error

Solution code:
N = int(input())
a = [int(input()) for _ in range(N)]
count = 0
i = 1
x = 0
osita = [0]*N
while 2 not in osita and count < N + 10:
    osita[x] = i
    i = a[i-1]
    count += 1
    x += 1
    
if count > N:
    print(-1)
else:
    print(count-1)

Submission status: Runtime Error

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]
  if on == 2:
    print(i)
    break
if i != 2:
  print(-1)

Submission status: Runtime Error

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

for i in range(N):
  if i == 0:
    nxt = a[0] - 1
  else:
    nxt = a[nxt]
    
  if nxt == 2:
    break
  else:
    cnt += 1

print(cnt)

Submission status: Runtime Error

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

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

Submission status: Runtime Error

Solution code:
n=int(input())
num=[0]
ans=0
count=0
k=1
for i in range(n):
    a=int(input())
    num.append(a)
 
 for i in range(n+1):
    k=num[k]
    count+=1
    if k==2:
        ans=1
        break
if ans==1:
    print(count)
else:
    print("-1")
# coding: utf-8

Submission status: Runtime Error

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

ans = 0
i = 0
while n > 0:
    ans += 1
    if a[i] == 2:
        print(ans)
        quit()
    else:
        i = a[i]-1
    n -= 1
print(-1)

Submission status: Runtime Error

Solution code:
N = int(input())
A = [int(input()) for i in range(N)]
def check_num(a,b):
    if b>N+1:
        return -1
    if A[a]==2:
        return b
    else:
        return check_num(int(A[a])-1,b+1)
print(check_num(0,1))

Submission status: Runtime Error

Solution code:
from copy import deepcopy
n = int(input())
lista = [[] for i in range(n + 1)]
ans = 10000000
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 == 10000000 else ans)

Submission status: Runtime Error

Solution code:
from copy import deepcopy
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: Runtime Error

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

Submission status: Runtime Error

Solution code:
n = int(input())
a = [int(input()) for i in range(n)]
check = [0 for i in rangen(n)]
now = 0
ans = 0
while check(now) != 0:
    if now == 1:
        print(ans)
        break
    check[now] = 1:
    now = a[now-1]
else:
    print(-1)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import java.util.*;

public class Main {

    public static void main(String args[]) {

        // 入力
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.next());
        Integer[] a = new Integer[n];
        Arrays.setAll(a, i -> Integer.parseInt(sc.next()));
        sc.close();

        // 主処理
        int target = 1;
        int count = 0;
        for (int i = 0; i < n; i++) {
            target = a[target - 1];
            count++;
            if (target == 2) {
                break;
            }
        }
        int result = target == 2 ? count : -1;

        // 出力
        System.out.println(result);
    }
}

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n=int(input())
a = [map(int,input() for _ in range(n))]
nex=[]
k=1
for i in range(len(a)):
    nex.append(a[k-1])
    k=nex[-1]
    if nex[-1]==2:
        print(len(nex))
        break
    elif len(nex)>=n:print(-1)
    else:pass

Submission status: Runtime Error

Solution code:
n=int(input())
a = [map(int,input()) for _ in range(n)]
nex=[]
k=1
for i in range(len(a)):
    nex.append(a[k-1])
    k=nex[-1]
    if nex[-1]==2:
        print(len(nex))
        break
    elif len(nex)>=n:print(-1)
    else:pass

Submission status: Runtime Error

Solution code:
n=int(input())
a = [input() for _ in range(n)]
nex=[]
k=1
for i in range(len(a)):
    nex.append(a[k-1])
    k=nex[-1]
    if nex[-1]==2:
        print(len(nex))
        break
    elif len(nex)>=n:print(-1)
    else:pass

Submission status: Runtime Error

Solution code:
from itertools import chain
n=int(input())
an= [list(input()) for _ in range(n)]
a=list(chain.from_iterable(an))
nex=[]
k=1
for i in range(len(a)):
    #if k-1==-1:k-1=0
    nex.append(a[k-1])
    k=nex[-1]
    if nex[-1]==2:
        print(len(nex))
        break
    elif len(nex)>=n:print(-1)
    else:pass

Submission status: Runtime Error

Solution code:
n=int(input())
a= [list(input()) for _ in range(n)]
nex=[]
k=1
for i in range(len(a)):
    #if k-1==-1:k-1=0
    nex.append(a[k-1])
    k=nex[-1]
    if nex[-1]==2:
        print(len(nex))
        break
    elif len(nex)>=n:print(-1)
    else:pass

Submission status: Runtime Error

Solution code:
import sys

N = int(input())
a = []
for _ in range(N):
    a.append(int(input()))
s = [0] * max(a)
s[0] = 1
count = 0
for _ in range(N):
    for i in range(N):
        if s[i] == 1:
            s[i] = 0
            s[a[i]-1] = 1
            break
    count += 1
    if s[1] == 1:
        print(count)
        sys.exit()
print(-1)

Submission status: Runtime Error

Solution code:
#ABC065.B
N = int(input())
a = [int(input()) for i in range(N)]
x = 0
for i in range(N):
    x = a[x]
    if x == 2:
        print(i+1)
        break
else:
    print(-1)

Submission status: Runtime Error

Solution code:
#ABC065.B
N = int(input())
a = [int(input()) for i in range(N)]
x = 0
for i in range(N):
    x = a[x]
    if a[x] == 2:
        print(i+1)
        break
else:
    print(-1)

Submission status: Runtime Error

Solution code:
#ABC065.B
N = int(input())
a = [int(input() for i in range(N))]
x = 0
for i in range(N):
    x = a[x]
    if a[x] == 2:
        print(i+1)
        break
else:
    print(-1)

Submission status: Runtime Error

Solution code:
import math
from collections import defaultdict

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

def check(key):
    # print(key)
    if key == 1:  # find goal
        return 1
    elif key == 2:  # forming infinite loop
        return math.inf
    else:
        values = a[key]
        if len(values) == 0:
            return math.inf
        return min([check(v) for v in values]) + 1

if a.get(2):
    ans = min([check(v) for v in a[2]])
else:
    ans = math.inf

if ans == math.inf:
    print(-1)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
import sys
inputs = list(map(int, sys.stdin))
N = inputs[0]
a = inputs[1:N]
isFound = False
ai = 1
for i in range(1, N + 1):
    ai = a[ai - 1]
#    print(f'a{i} = {ai}')
    if (ai == 2):
        isFound = True
        print(i)
        break
if (isFound is False):
    print(-1)

Submission status: Runtime Error

Solution code:
import sys
Input = list(map(int, sys.stdin))
N = Input[0]
a = Input[1:N]
isFound = False
ai = 1
for i in range(1, N + 1):
    ai = a[ai - 1]
#    print(f'a{i} = {ai}')
    if (ai == 2):
        isFound = True
        print(i)
        break
if (isFound is False):
    print(-1)

Submission status: Runtime Error

Solution code:
visited = [0]*n
ans = 0
i = 0
while True:
  i = A[i]
  ans += 1  
  if visited[i]==1:
    ans = -1
    break    
  visited[i] = 1
  if i == 1:
    break
  
print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n = int(input())
A = [int(input()) for _ in range(n)]
used = {1}
pos = 1
count = 0
for _ in range(n):
  pos = A[pos - 1]
  count += 1
  if pos in used:
    print(-1)
    break
  used.append(pos)
  if pos == 2:
    print(count)
    break

Submission status: Runtime Error

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

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

Submission status: Runtime Error

Solution code:
N = int(input())
D = {i+1:int(input()) for i in range(N)}
d = D{1}
ans = 1


for i in range(N):
  if d==2:
    print(ans)
    exit()
    
  d = D[d]
  ans +=1
  
  
print(-1)

Submission status: Runtime Error

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

ans = 0
check = []
tmp = 1
check.append(tmp)
flag = False
while(1):
    tmp = a[tmp]
    ans += 1
    if tmp==2:
        flag = True
        break
    if tmp in check:
        break
if flag:
    print(ans)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
#065b
N = int(input())
a_list=[0]

for i in range(N):
    ai = int(input())
    a_list.append(ai)

def push_button(pushed_button,pushed_button_set):
	if pushed_button == 2:
		print(len(pushed_button_set))
	else:
		if pushed_button in pushed_button_set:
			print(-1)
			return -1
		else:
			pushed_button_set.add(pushed_button)
			push_button(a_list[pushed_button],pushed_button_set)
			
push_button(1,set())

Submission status: Runtime Error

Solution code:
N = str(input())
list=[]
for i in range(N):
    list.append(int(input()))
count=0
X=list[0]
while True:
    X=list[X-1]
    count+=1
    if X == 2:
        print(count+1)
    if count == 100000:
        print(-1)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
N = int(input())
a = []
for _ in range(N):
    a.append(int(input()))
x = 1
visited = set([1])
answer = 0

while True:
    x = a[x]
    if x in visited:
        answer = -1
        break
    visited.add(x)
    answer += 1
    if x == 2:
        break

print(answer)

Submission status: Runtime Error

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

def search(A):
    answer += 1
    if A in count or answer > N:  # ループ処理
        print(-1)
        exit()
    count.append(A)
    print(count)
    if A == 2:
        print(len(count) - 1)
        exit()

    search(a[A-1])

search(a[0])

Submission status: Runtime Error

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

def search(A):
    if A in count:  # ループ処理
        print(-1)
        exit()
    count.append(A)
    # print(count)
    if A == 2:
        print(len(count) - 1)
        exit()
        
    search(a[A-1])

search(a[0])

Submission status: Runtime Error

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

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

print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())

V = []
seen = [False]*N

for _ in range(N):
    V.append(set())
index = 0
for _ in range(N):
    next_node = int(input())

    V[index].add(next_node-1)
    index = index + 1
min = float('inf')

def dfs(node, count):
    global min

    if seen[node]==True:
        return
    if node==1:
        if min > count:
            min = count
        return

    seen[node]=True
    for next_node in V[node]:
        dfs(next_node, count+1)

dfs(0,0)
if min==float('inf'):
    print(-1)
else:
    print(min)

Submission status: Runtime Error

Solution code:
n=int(input())
a = [int(input()) for _ in range(n)]
position = a.index(2)
if position == False:
  print(str(-1))
  exit()
position = position + 1
for i in range(n+1): # 最高でもn+!回だけ探してやれば十分
  position = a.index(position) + 1
  if position==1:
    print(str(i+2))
    exit()
print(str(-1))

Submission status: Runtime Error

Solution code:
n=int(input())
a = [int(input()) for _ in range(n)]
position = a.index(2)
if position == False:
  print(-1)
  exit()
position = position + 1
for i in range(n+1): # 最高でもn+!回だけ探してやれば十分
  position = a.index(position) + 1
  if position==1:
    print(i+2)
    exit()
print(-1)
exit()

Submission status: Runtime Error

Solution code:
n=int(input())
a = [int(input()) for _ in range(n)]
position = a.index(2) + 1
if position == False:
  print(-1)
  exit()
for i in range(n+1): # 最高でもn+!回だけ探してやれば十分
  position = a.index(position) + 1
  if position==1:
    print(i+2)
    exit()
print(-1)
exit()

Submission status: Runtime Error

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

num = 0
now = 0
been = set()
been.add(0)

while now != 1:
    now = a[now] - 1
    if now in been:
        num = -1
        break
    else:
        been.add(now)
        num += 1

print(num)

Submission status: Runtime Error

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

i = 0
cnt = 0
while not i == 1:
    i = a[i] - 1
    cnt += 1
    if i >= n or cnt > 100000:
        exit("-1")
print(cnt)

Submission status: Runtime Error

Solution code:
あ

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N, btn;
  cin >> N;
  btn = 1;
  
  vector<int> a(N);
  for (int i = 0; i < N; i++) {
    cin >> a.at(i);
  }
  
  for (int i = 0; i < N; i++) {
    if (btn == 2) {
      cout << i << endl;
      break;
    }
    btn = a.at(btn - 1);
  }
  
  if (btn != 2) {
    cout << -1 << endl;
  }
}

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N, btn;
  cin >> N;
  btn = 1
  
  vector<int> a(N);
  for (int i = 0; i < N; i++) {
    cin >> a.at(i);
  }
  
  for (int i = 0; i < N; i++) {
    if (btn == 2) {
      cout << i << endl;
      break;
    }
    btn = a.at(btn - 1);
  }
  
  if (btn != 2) {
    cout << -1 << endl;
  }
}

Submission status: Runtime Error

Solution code:
#変数に注意。。。#
def f(n,l):
  m=A[n]
  if m==1:
    print(l)
  elif L[m]==1:
    print(-1)
  else:
    L[m]=1
    return f(m,l+1)

N=int(input())
L=[0 for i in range(N)]
A=[int(input())-1  for _ in range(N)]
L[0]=1
f(0,1)

Submission status: Runtime Error

Solution code:
def f(n):
  m=A[n]
  if m==1:
    print(n)
  elif L[m]==1:
    print(-1)
  else:
    n+=1
    L[m]=1
    return f(m)

N=int(input())
L=[0 for i in range(N)]
A=[int(input())-1  for _ in range(N)]
L[0]=1
n=0
if A[0]==1:
  print(1)
else:
  f(0)

Submission status: Runtime Error

Solution code:
def f(n):
  m=A[n]
  if m==1:
    print(n)
  elif L[m]==1:
    print(-1)
  else:
    n+=1
    L[m]=1
    return f(m)

N=int(input())
L=[0 for i in range(N)]
A=[int(input())-1  for _ in range(N)]
L[0]=1
n=0
f(0)

Submission status: Runtime Error

Solution code:
N = int(input())
light_rule = {n:int(input())-1 for n in range(N)}

light = ["1"]+["0"]*(N-1)

flag = 0
num = 0
bottun = 0
for _ in range(1e6):
    if light[1] == "1":
        flag = 1
        break
    num += 1
    # print(bottun, light_rule[bottun])
    light[bottun] = "0"
    light[light_rule[bottun]] = "1"
    bottun = light_rule[bottun]
    # print(light)
    
if flag:
    print(num)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
N = int(input())
light_rule = {n:int(input())-1 for n in range(N)}

light = ["1"]+["0"]*(N-1)

flag = 0
num = 0
bottun = 0
for _ in range(N):
    if light[2] == "1":
        flag = 1
        break
    num += 1
    # print(bottun, light_rule[bottun])
    light[bottun] = "0"
    light[light_rule[bottun]] = "1"
    bottun = light_rule[bottun]
    # print(light)
    
if flag:
    print(num)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
N = int(input())
light_rule = {n:int(input())-1 for n in range(N)}

light = ["1"]+["0"]*(N-1)
searched = {"".join(light):1}

flag = 0
num = 0
bottun = 0
for _ in range(N):
    if light[2] == "1":
        flag = 1
        break
    num += 1
    # print(bottun, light_rule[bottun])
    light[bottun] = "0"
    light[light_rule[bottun]] = "1"
    bottun = light_rule[bottun]
    # print(light)
    if searched.get("".join(light)):
        break
    else:
        searched["".join(light)] = 1
    
if flag:
    print(num)
else:
    print(-1)

Submission status: Runtime Error

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

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

Submission status: Runtime Error

Solution code:
N = int(input())
A = [int(input()) for i in range(N)]
Next = 0
for i in range(N):
  if Next == 2:
    Next = A[Next]
    p = i
    break;
  else:
    Next = A[Next-1]
    p = -1
print(p)

Submission status: Runtime Error

Solution code:
n=int(input())
s=[]
k=s[0]
ans=0
for i in range(n):
  a=int(input())
  s.append(a)
for j in range(n+1):
  if s[k]==2:
    ans+=1
    print(ans)
    exit()
  else:
    ans+=1
    k=s[s[k]]
print(-1)

Submission status: Runtime Error

Solution code:
N = int(input())
dic = {}
for i in range(N):
  a = int(input())
  dic[i+1] = a
counter = 0
place = 1
while place != 2:
  if dic[place] in dic:
    temp = dic[place]
    dic.pop(place)
    place = temp
    counter += 1
  else:
    counter = -1
    break

print(counter)

Submission status: Runtime Error

Solution code:
def bfs(n,e,fordfs):
    #点の数、スタートの点、有向グラフ
    W = [-1]*n
    #各点の状態量、最短距離とか,見たかどうかとか
    W[e] = 0
    que = deque()
    que.append(e)
    len = [float("inf")]*n
    len[e] = 0
    while que:
        now = que.popleft()
        nowv = W[now]
        nowlen = len[now]
        for ne in fordfs[now]:
            if nowv == W[ne]:
                #ループが嫌な時
                return -1
            elif W[ne] == -1:
                W[ne] = (nowv+1) % 2
                len[ne] = nowlen+1
                que.append(ne)
    return len


def examB():
    N = I()
    v = [[]for _ in range(N)]
    for i in range(N):
        a = I()
        v[i].append(a-1)
    v[1]=[]
    b = bfs(N,0,v)
    ans = b[1]
    if ans==float("inf"):
        ans = -1
    print(ans)

import sys
import copy
import bisect
import heapq
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')

examB()

Submission status: Runtime Error

Solution code:
n = int(input())
A = [ int(input()) for i in range(n) ]
c = 0
temp = 1
s = {1}
while temp not in s:
  temp = A[temp-1]
  c += 1
  i temp == 2:
    print(c)
    exit()
  s.add(temp)
print(-1)

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
print((n-1)*(m-1))

Submission status: Runtime Error

Solution code:
#065b
N = int(input())
a_list=[0]

for i in range(N):
    ai = int(input())
    a_list.append(ai)
    
def push_button(pushed_button,ans):
    ans += 1
    #print(ans,":",pushed_button,a_list[pushed_button])
    
    if a_list[pushed_button] == 2:
        return ans
    elif a_list[pushed_button] == pushed_button or pushed_button == a_list[a_list[pushed_button]]:
        return -1
    else:
        ans = push_button(a_list[pushed_button],ans)
        return ans
        
#print(a_list)
print(push_button(1,0))

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n = int(input())
a = [int(input()) for _ in range(n)]
tmp = a[0]
if a.index(2) == -1:
    print(-1)
else:
    ans = -1
    count = 0
    while(tmp != 1):
        count += 1
        if tmp == 2:
            ans = count
            break
        tmp = a[tmp - 1]
print(ans)

Submission status: Runtime Error

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

now = 1
flag = 1
memo = []
cnt = 0
for i in range(N)
    next = a_lis[now-1]
    if next in memo:
        print(-1)
        flag = 0
        break
    else:
        memo.append(next)
        now = next
    cnt+=1
    if next ==2:
        print(cnt)
        break

Submission status: Runtime Error

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

Submission status: Runtime Error

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

a=[int(i)-1 for i in sys.stdin]
N=l[0]+1
a=a[1:]

done=[False]*N

ans=0
i=0

while True:
  if done[i]==False:
    done[i]=True
    ans+=1
    if a[i]==1:
      break
    i=a[i]

  
  else:
    ans=-1
    break
    
print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding:utf-8 -*-
N=int(input())
button=[]
for i in range(N):
  button.append(int(input()))

number=0
count=0
footprint=[0]
while number!=1:
  number=button[number]-1
  count+=1
    if number in footprint:
      print(-1)
      exit()
  footprint.append(number)
print(count)

Submission status: Runtime Error

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

for n in range(N):
  a=int(input())
  li.append(a)

s=0
count=0

while s!=1:
  if count==N:
    break
  else:
    check.append(s)
    s=li[s]-1
    count+=1

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

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)
def search(arr, num, i):
  nxt = arr[num]
  if(nxt == 1):
    return i
  elif(i >= len(arr)):
    return -1
  else:
    return search(arr, nxt, i+1)

n = int(input())
a = [ int(input()) - 1 for _ in range(n)]
print(search(a, 0, 1))

Submission status: Runtime Error

Solution code:
sys.setrecursionlimit(10000)
def search(arr, num, i):
  nxt = arr[num]
  if(nxt == 1):
    return i
  elif(i >= len(arr)):
    return -1
  else:
    return search(arr, nxt, i+1)

n = int(input())
a = [ int(input()) - 1 for _ in range(n)]
print(search(a, 0, 1))

Submission status: Runtime Error

Solution code:
def search(arr, num, i):
  nxt = arr[num]
  if(nxt == 1):
    return i
  elif(i >= len(arr)):
    return -1
  else:
    return search(arr, nxt, i+1)

n = int(input())
a = [ int(input()) - 1 for _ in range(n)]
print(search(a, 0, 1))

Submission status: Runtime Error

Solution code:
def search(a, num, i):
  nxt = a[num]
  if(nxt == 1):
    return i
  elif(i >= len(a)):
    return -1
  else:
    return search(a, nxt, i+1)

n = int(input())
a = [ int(input()) - 1 for _ in range(n)]
print(search(a, 0, 1))

Submission status: Runtime Error

Solution code:
def search(a, num, i):
  nxt = a[num]
  if(nxt == 1):
    return i
  elif(i >= len(a)):
    return -1
  else:
    return search(a, nxt, i+1)

n = int(input())
a = [ int(input())-1 for _ in range(n)]
print(search(a, 0, 1))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N;
  cin >> N;

  vector<int> a(N, 0);
  for (int i; i < N; i++) {
    cin >> a[i];
  }

  int ans = -1, tmp = 0;

  for (int i = 0; i < N; i++) {
    tmp = a[tmp] - 1;
    if (tmp == 1) {
      ans = i + 1;
      break;
    }
  }

  cout << ans << endl;
}

Submission status: Runtime Error

Solution code:
n = int(input())
a = [int(input())-1 for i in range(n)]
#ボタンを押す=listから値を取得して-1にする
#取得した値=光っているボタンの番号
#光っているボタンの番号が1ならbreak
#取得した値が-1なら2を通らずループしてしまっている
sb = 0
ans = 0
for i in range(n):
    if sb == 1:
        flag = True
        break
    elif sb == -1:
        flag = False
        break
    tmp = a[sb]
    a[sb] = -1
    sb = tmp
    ans += 1
if flag:
    print(ans)
else:
    print(-1)

Submission status: Runtime Error

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

now = 0
count = 0
while True:
    if now == 1:
        print(count)
        break
    elif c >= n:
        print(-1)
        break
    else:
        count += 1
        now = alist[now]

Submission status: Runtime Error

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

now = 0
count = 0
while True:
    if now == 1:
        print(coount)
        break
    elif c >= n:
        print(-1)
        break
    else:
        count += 1
        now = alist[now]

Submission status: Runtime Error

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

now = 0
count = 0
while True:
    if now == 1:
        print(c)
        break
    elif c >= n:
        print(-1)
        break
    else:
        count += 1
        now = alist[now]