Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10 ** 6)


def dfs(n, pn):
    nn = edge[n]
    if nn == pn:
        game.append(n)
        game.append(pn)
    elif track[nn] == 0:
        track[nn] = 1
        dfs(nn, n)


N = int(input())

G = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
cur = [0] * N
edge = [0] * N
for i in range(N):
    edge[i] = G[i][cur[i]]

day = 0
cnt = 0
while cnt < N:
    day += 1
    track = [0] * N
    game = []
    for i in range(N):
        if track[i] == 0:
            track[i] = 1
            dfs(i, -1)
    if len(game) == 0:
        print(-1)
        exit()
    else:
        for j in game:
            cur[j] += 1
            c = cur[j]
            if c >= N - 1:
                edge[j] = j
                cnt += 1
            else:
                edge[j] = G[j][c]

print(day)


### FIXED CODE ###

N = int(input())

G = [list(map(int, input().split())) for _ in range(N)]
cur = [0] * N
edge = [0] * N
for i in range(N):
    edge[i] = G[i][0] - 1

day = 0
player = set(range(N))
cnt = 0
while len(player) > 0:
    day += 1
    game = set()
    for i in player:
        e = edge[i]
        if i == edge[e] and i != e:
            game.add(i)
            game.add(e)
    player = set()
    for j in game:
        cur[j] += 1
        c = cur[j]
        if c >= N - 1:
            edge[j] = j
        else:
            edge[j] = G[j][c] - 1
            player.add(j)

if min(cur) != N - 1:
    ans = -1
else:
    ans = day
print(ans)
### BUGGY CODE ###

def main():
    n=int(input())
    s=input()
    S=[int(x) for x in list(s)]
    Pass=[0]*1000
    z=S[0]*100+S[1]*10+S[2]
    Pass[z]=1
    for k in S[3:]:
        s=set()
        for p in range(1000):
            p1,p2,p3=p//100,(p//10)%10,p%10
            if Pass[p]==1:
                s.add(p2*100+p3*10+k)
                s.add(p1*100+p3*10+k)
                s.add(p1*100+p2*10+k)
        for k in s:
            Pass[k]=1
    print(sum(Pass))
    
if __name__=='__main__':
    main()

### FIXED CODE ###

def main():
    n=int(input())
    s=input()
    S=[int(x) for x in list(s)]
    Pass1={S[0],S[1],S[2]}
    Pass2={S[0]*10+S[1],S[0]*10+S[2],S[1]*10+S[2]}
    Pass3={S[0]*100+S[1]*10+S[2]}
    for k in S[3:]:
        for i in Pass2:
            Pass3.add(i*10+k)
        for i in Pass1:
            Pass2.add(i*10+k)
        Pass1.add(k)
    print(len(Pass3))
    
if __name__=='__main__':
    main()
### BUGGY CODE ###

import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


N, X = LI()
X_list = LI()
#  if N == 1:
#      print(abs(X_list[0] - 1))
#      exit()
X_list.sort()

bisect.insort_left(X_list, X)
#  print(X_list)
X_diff = [j-i for i, j in zip(X_list[:-1], X_list[1:])]
result = min(X_diff)
# 全部行けない場合がある
# 1 4 9 など
# すべてステップ幅-1で割り切れなければ不可

results = []
for i in range(1, result+1):
    if all(x % i == 0 for x in X_diff):
        results.append(i)

print(results[-1])


### FIXED CODE ###

import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


N, X = LI()
X_list = LI()

#  N = 10**5
#  X = 10**9
#  X_list = [i for i in range(1, 10**5, 5)]

#  if N == 1:
#      print(abs(X_list[0] - 1))
#      exit()
X_list.sort()

bisect.insort_left(X_list, X)
#  print(X_list)
X_diff = [abs(j-i) for i, j in zip(X_list[:-1], X_list[1:])]
X_diff = list(set(X_diff))
#  result = min(X_diff)
# 全部行けない場合がある
# 1 4 9 など
# すべてステップ幅-1で割り切れなければ不可

def gcd(a,b):
    if b == 0: return a
    return gcd(b, a%b)

for i in range(len(X_diff)):
    #  print(i)
    if i == 0:
        result = X_diff[i]
        continue
    
    result = gcd(X_diff[i], result)
#  while True:
#      if all(x % result == 0 for x in X_diff):
#          result = i
#      else:
#          result = [i for i in range(result, 0, -1) if ]

print(result)
### BUGGY CODE ###

n = int(input())
p = list(map(int,input().split()))
tmp = []
ans = 0
for i in range(n):
    tmp.append(p[i])
    if min(tmp)>=p[i]:
        ans+=1
print(ans)

### FIXED CODE ###

n = int(input())
p = list(map(int,input().split()))
mtmp = p[0]
ans = 0
for i in range(0,n):
    if mtmp>=p[i]:
        mtmp=p[i]
        ans+=1
print(ans)
### BUGGY CODE ###

N,W = map(int, input().split())
w = [0]*N
v = [0]*N
for i in range(N):
    w[i],v[i] = map(int, input().split())

dp = [[0 for i in range(W)] for j in range(N)]

for i in range(N):
    for j in range(w[i]-1,W):
        dp[i][j] = v[i]

for i in range(1,N):
    for j in range(W):
        if j >= w[i]:
            dp[i][j] = max(dp[i][j],dp[i-1][j],dp[i-1][j-w[i]]+v[i])
        else:
            dp[i][j] = max(dp[i][j],dp[i-1][j])
print(dp[-1][-1])


### FIXED CODE ###

#PythonだとTLE、PyPyだとAC
N,W = map(int, input().split())
w = [0]*N
v = [0]*N
for i in range(N):
    w[i],v[i] = map(int, input().split())

V = sum(v)
inf=float("inf")
dp = [[inf for i in range(V)] for j in range(N)]

for i in range(N):
    for j in range(v[i]):
        dp[i][j] = w[i]

for i in range(1,N):
    for j in range(V):
        if j >= v[i]:
            dp[i][j] = min(dp[i][j],dp[i-1][j],dp[i-1][j-v[i]]+w[i])
        else:
            dp[i][j] = min(dp[i][j],dp[i-1][j])

cnt = 0
for i in dp[-1]:
    if i <= W:
        cnt += 1
print(cnt)
### BUGGY CODE ###

def examA():
    S = SI(); N = len(S)
    prev = S[0]; cur = ""
    k = 0; ans = 1
    while(k<N-1):
        k +=1
        cur += S[k]
        if cur==prev:
            continue
        prev = cur
        cur = ""
        ans +=1
    print(ans)
    return

def examB():
    N = I()
    S = SI()
    return

def examC():
    N = I()
    A = LI()
    B = LI()
    ans = 0
    que = []
    for i in range(N):
        que.append((-B[i],i))
    heapify(que)
    flag = True
    while(que):
        b,i = heappop(que)
        b *=(-1)
        if b == A[i]:
            continue
        a, c = B[(i - 1) % N], B[(i + 1) % N]
        if b - A[i] < a + c:
            flag = False
            break
        r = (b - A[i]) // (a + c)
        b -= (a + c) * r
        B[i] = b
        ans += r
        if b != A[i]:
            heapq.heappush(que, (-b, i))
#    print(que)
#    print(K)
    if flag:
        print(ans)
    else:
        print(-1)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18

if __name__ == '__main__':
    examC()


### FIXED CODE ###

def examA():
    S = SI(); N = len(S)
    prev = S[0]; cur = ""
    k = 0; ans = 1
    while(k<N-1):
        k +=1
        cur += S[k]
        if cur==prev:
            continue
        prev = cur
        cur = ""
        ans +=1
    print(ans)
    return

def examB():
    N = I()
    S = SI()
    return

def examC():
    N = I()
    A = LI()
    B = LI()
    ans = 0
    que = []
    for i in range(N):
        heappush(que,(-B[i],i))
    flag = True
    while(que):
        b,i = heappop(que)
        b *=(-1)
        if b == A[i]:
            continue
        a, c = B[(i - 1) % N], B[(i + 1) % N]
        if b - A[i] < a + c:
            flag = False
            break
        r = (b - A[i]) // (a + c)
        b -= (a + c) * r
        B[i] = b
        ans += r
        if b != A[i]:
            heapq.heappush(que, (-b, i))
#    print(que)
#    print(K)
    if flag:
        print(ans)
    else:
        print(-1)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18

if __name__ == '__main__':
    examC()
### BUGGY CODE ###

import bisect
from collections import defaultdict as dd
n, m, q = map(int, input().split())
Tr = []
L2Rs = dd(lambda: [])
for i in range(m):
  l, r = map(int, input().split())
  Tr.append([l, r])
  L2Rs[l] += [r]
Tr.sort(key=lambda x: x[0])
for i in L2Rs.keys():
  L2Rs[i] = sorted(L2Rs[i])
L = L2Rs.keys()
  
Sc = []
for i in range(q):
  Sc.append(list(map(int, input().split())))
#Sc.sort(key=lambda x: x[0])
#print(Sc)

for i in range(q):
  left, right = Sc[i]
  counter = 0
  for j in range(left, 500):
    #print(j, L2Rs[j], left, right)
    r_ok = bisect.bisect_right(L2Rs[j], right)
    #print(r_ok)
    counter += r_ok
  print(counter)

### FIXED CODE ###

n, m, q = map(int, input().split())
Arr = []
for i in range(n+1):
  Arr.append([0] * (n+1))
for i in range(m):
  l, r = map(int, input().split())
  Arr[l][r] += 1
#print(Arr)

B = []
for i in range(n+1):
  B_line = [0]
  for j in range(1, n+1):
    B_line.append(B_line[-1] + Arr[i][j])
  B.append(B_line)
#print(B)
  
for x in range(q):
  left, right = map(int, input().split())
  train_num = 0
  for i in range(left, right+1):
    train_num += B[i][right] - B[i][left-1]
  print(train_num)
### BUGGY CODE ###

r, g, b, n = map(int, input().split())
cnt = 0
for i in range(n // r + 1):
    for j in range((n - i) // g + 1):
        k = (n - i * r - j * g) / b
        if k >= 0 and k // 1 == k:
            cnt += 1
print(cnt)

### FIXED CODE ###

r, g, b, n = map(int, input().split())
cnt = 0
for i in range(0, n + 1, r):
    for j in range(0, n - i + 1, g):
        if (n - i - j) % b == 0:
            cnt += 1
print(cnt)
### BUGGY CODE ###

# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

#n,k,*a = map(int,read().split())
n, = map(int,readline().split())
vw = [(0,0)]+[tuple(map(int,readline().split())) for _ in range(n)]

A = 10
N = min(1<<A,n+1)

memo = [None for _ in range(N)]
L = 10**5+1
memo[0] = [0]*L

for i in range(1,N):
    m = memo[i>>1][:]
    v,w = vw[i]    
    for j in range(L-1,w-1,-1):
        if m[j] < m[j-w]+v:
            m[j] = m[j-w]+v
    memo[i] = m

q, = map(int,readline().split())
for _ in range(q):
    u,l = map(int,readline().split())

    dv = [0]
    dw = [0]
    while u >= N:
        dv += [vw[u][0]+v1 for v1 in dv]
        dw += [vw[u][1]+w1 for w1 in dw]
        u >>= 1
    
    ans = 0
    for v,w in zip(dv,dw):
        if w <= l:
            ans = max(ans,memo[u][l-w]+v)
    print(ans)

        


### FIXED CODE ###

# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

#n,k,*a = map(int,read().split())

n, = map(int,readline().split())
vw = [[0,0]]+[list(map(int,readline().split())) for _ in range(n)]

def merge(av,aw,bv,bw):
    la,lb = len(aw),len(bw)
    rv = [0]*(la+lb)
    rw = [0]*(la+lb)
    ia = ib = 0
    for i in range(la+lb):
        if ib==lb or (ia < la and aw[ia] < bw[ib]):
            rv[i] = av[ia]
            rw[i] = aw[ia]
            ia += 1
        else:
            rv[i] = bv[ib]
            rw[i] = bw[ib]
            ib += 1
    return rv,rw

A = 10
N = min(1<<A,n+1)
memov = [[] for _ in range(N)]
memow = [[] for _ in range(N)]

memov[0] = [0]
memow[0] = [0]

#from itertools import acumulate
for i in range(1,N):
    v,w = vw[i]
    m2v = [v+v1 for v1 in memov[i>>1]]
    m2w = [w+w1 for w1 in memow[i>>1]]
    memov[i],memow[i] = merge(memov[i>>1],memow[i>>1],m2v,m2w)

    #memov[i] = list(accumulate(memov[i],max))
    for j in range(1,len(memov[i])):
        memov[i][j] = max(memov[i][j-1],memov[i][j])
    
def solve(lstv,lstw,dv,dw,l):
    ans = 0
    idx = len(lstw)-1
    #print(lstv,lstw,dv,dw,l)
    for v,w in zip(dv,dw):
        while idx >= 0 and lstw[idx] + w > l:
            idx -= 1
        if idx >= 0 and v+lstv[idx] > ans:
            ans = v+lstv[idx]
    print(ans)        
 
 

q, = map(int,readline().split())
for _ in range(q):
    u,l = map(int,readline().split())

    dv = [0]
    dw = [0]
    while u >= N:
        v,w = vw[u]
        m2v = [v+v1 for v1 in dv]
        m2w = [w+w1 for w1 in dw]
        dv,dw = merge(dv,dw,m2v,m2w)
        u >>= 1
    
    #for j in range(1,len(dv)):
    #    dv[j] = max(dv[j-1],dv[j])
    
    solve(memov[u],memow[u],dv,dw,l)

#print(memov)
#print(memow)
### BUGGY CODE ###

from collections import deque

MOD = 10**9+7
n, k = map(int,input().split())
e = [[] for i in range(n)]
for i in range(n-1):
    a, b = map(int,input().split())
    a -= 1
    b -= 1
    e[a].append(b)
    e[b].append(a)
    
color = [-1]*n
color[0] = k
d = deque()
d.append(0)
while d:
    f = d.pop()
    tmp = deque()
    tmp.append([f, 0])
    cnt = 0
    while tmp:
        cf, cd = tmp.pop()
        if cd >= 2:
          break
        for i in e[cf]:
            if i == f:
                continue
            if color[i] != -1:
                cnt += 1
                tmp.appendleft([i, cd+1])
    color[f] = k - cnt
    for i in e[f]:
        if color[i] == -1:
            d.appendleft(i)
            
ans = 1
for i in range(n):
    ans = ans * color[i] % MOD
print(ans)

### FIXED CODE ###

# -*- coding: utf-8 -*-
"""
Created on Tue Aug 25 08:44:21 2020

@author: teppe
"""

from collections import deque

def prepare(n, MOD):
 
    # 1! - n! の計算
    f = 1
    factorials = [1]  # 0!の分
    for m in range(1, n + 1):
        f *= m
        f %= MOD
        factorials.append(f)
    # n!^-1 の計算
    inv = pow(f, MOD - 2, MOD)
    # n!^-1 - 1!^-1 の計算
    invs = [1] * (n + 1)
    invs[n] = inv
    for m in range(n, 1, -1):
        inv *= m
        inv %= MOD
        invs[m - 1] = inv
     
    return factorials, invs

MOD = 10**9+7
fact, fact_inv = prepare(10+10**5, MOD)

def perm(n,k):
  if k > n or k < 0:
    return 0
  return fact[n] * fact_inv[n-k] % MOD


n, k = map(int,input().split())
e = [[] for i in range(n)]
for i in range(n-1):
    a, b = map(int,input().split())
    a -= 1
    b -= 1
    e[a].append(b)
    e[b].append(a)
 
colored = [False]*n
colored[0] = True
num = len(e[0])
ans = perm(k, 1+num)
d = deque()
for i in e[0]:
    colored[i] = True
    d.append(i)
while d:
    f = d.pop()
    num = len(e[f]) - 1
    if num == 0:
        continue
    ans *= perm(k-2, num)
    ans %= MOD
    for i in e[f]:
        if not colored[i]:
            colored[i] = True
            d.appendleft(i)
print(ans % MOD)
### BUGGY CODE ###

from collections import deque
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = [list(map(int, input().split())) for i in range(m)]

mn = min(a)
for i in b:
    if i[1] < mn:
        continue
    a.extend([i[1]] * i[0])

a.sort(reverse=True)
print(sum(a[:n]))

### FIXED CODE ###

from collections import Counter
n, m = map(int, input().split())
a = Counter(list(map(int, input().split())))

for i in range(m):
    b, c = map(int, input().split())
    a[c] += b

num = sorted(a.items(), key=lambda x: x[0], reverse=True)
ans = 0

for key, val in num:
    if n > val:
        ans += key * val
        n -= val
    else:
        ans += key * n
        break

print(ans)
### BUGGY CODE ###

import sys
input=sys.stdin.readline
h,w = map(int, input().split())
a=[list(map(int,input().split())) for i in range(h)]
b=[list(map(int,input().split())) for i in range(h)]
d = [[0 for j in range(w)] for i in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            nxt=d[nowh][nxtw]
            if k+nxt < 6400:
                dp[nowh*w + nxtw][k+nxt] = 1
            dp[nowh*w + nxtw][abs(k-nxt)] = 1
        if nxth<h:
            nxt=d[nxth][noww]
            if k+nxt < 6400:
                dp[nxth*w + noww][k+nxt] = 1
            dp[nxth*w + noww][abs(k-nxt)] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

### FIXED CODE ###

h,w = map(int, input().split())
a=[list(map(int,input().split())) for i in range(h)]
b=[list(map(int,input().split())) for i in range(h)]
d = [[0 for j in range(w)] for i in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            if k+d[nowh][nxtw] < 6400:
                dp[nowh*w + nxtw][k+d[nowh][nxtw]] = 1
            dp[nowh*w + nxtw][abs(k-d[nowh][nxtw])] = 1
        if nxth<h:
            if k+ d[nxth][noww]< 6400:
                dp[nxth*w + noww][k+d[nxth][noww]] = 1
            dp[nxth*w + noww][abs(k-d[nxth][noww])] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()
### BUGGY CODE ###

from collections import defaultdict

MOD = 10 ** 9 + 7

n = int(input())
a = list(map(int, input().split()))

def factorize(n):
    res = defaultdict(int)
    d = 2
    while d * d <= n:
        while n % d == 0:
            n //= d
            res[d] += 1
        d += 1
    if n > 1:
        res[n] += 1
    return res

factors = [factorize(val) for val in a]
lcm = defaultdict(int)
for d in factors:
    for num in d.keys():
        lcm[num] = max(lcm[num], d[num])

ret = 0
for i, d in enumerate(factors):
    val = 1
    for num in lcm.keys():
        val *= pow(num, lcm[num] - d[num], MOD)
        val %= MOD
    ret += val
    ret %= MOD
print(ret)

### FIXED CODE ###

from functools import reduce

MOD = 10 ** 9 + 7

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def getLcm(a, b):
    return a * b // gcd(a, b)

def lcmArr(a):
    return reduce(getLcm, a)

n = int(input())
a = list(map(int, input().split()))

lcm = lcmArr(a)
lcm %= MOD
ret = 0
for val in a:
    ret += lcm * pow(val, MOD - 2, MOD)
    ret %= MOD
print(ret)
### BUGGY CODE ###

n = int(input())
a = list(map(int, input().split()))
sa = sorted(a)
for i in range(n):
    if sa.index(a[i])<n//2: print(sa[n//2])
    else: print(sa[n//2-1])

### FIXED CODE ###

n,*x=map(int, open(0).read().split());xc=sorted(x);
for i in x:print(xc[n//2-(i>(xc[n//2-1]+xc[n//2])/2)])
### BUGGY CODE ###

a,b,k = map(int,input().split())

for i in range(k):
  if a >= 1:
    a -= 1
  elif b >= 1:
    b -= 1
  else:
    pass

print(a,b)

### FIXED CODE ###

a,b,k = map(int,input().split())

if a > k:
  print(a-k,b)
elif a == k:
  print(0,b)
else:
  if (a+b) > k:
    print(0,a+b-k)
  else:
    print(0,0)
### BUGGY CODE ###

import collections
n = int(input())
ls = [input() for i in range(n)]    
c = collections.Counter(ls)
count = c.most_common()[0][1]
ans = []
if c.most_common()[0][1] == 1:
    ls.sort()
    for i in ls:
        print(i)
else:
    for i in range(len(c)):
        if c.most_common()[i][1] == count:
            ans.append(c.most_common()[i][0])
        else:
            break   
    ans.sort()
    for i in ans:
      print(i)

### FIXED CODE ###

import collections
from collections import Counter

n = int(input())
ls = [input() for i in range(n)]    
c = Counter(ls).most_common()

count = c[0][1]
ans = []

for i in range(len(c)):
    if c[i][1] == count:
        ans.append(c[i][0])
    else:
        break   
ans = sorted(ans)
for i in ans:
    print(i)
### BUGGY CODE ###

n,m = map(int,input().split(" "))
card = {i+1 for i in range(n)}

for i in range(m):
    l,r = map(int,input().split(" "))
    tmp = set()
    for j in range(l,r+1):
        tmp.add(j)

    card = card.intersection(tmp)
print(len(card))

### FIXED CODE ###

n,m = map(int,input().split(" "))

x,y = map(int,input().split(" "))
for i in range(m-1):
    l,r = map(int,input().split(" "))
    x = max(x,l)
    y = min(y,r)

if y-x >= 0:
    print(y-x+1)
else:
    print(0)
### BUGGY CODE ###

n = int(input())
a = list(map(int, input().split()))
result = 1
checker =False
for j in a:
  if j > 1000000000000000000:
    result = -1
    checker =True
if 0 in a:
  result = 0
  checker=True
while checker==False:
  for i in range(len(a)):
    result = result*a[i]
  checker = True
    

if result <= 1000000000000000000:
  print(result)
else:
  print(-1)


### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
a.sort()
result = 1
for i in range(len(a)):
  result = result*a[i]
  if result == 0:
    break
  elif result > 1000000000000000000:
    break

if result <= 1000000000000000000:
  print(result)
else:
  print(-1)
### BUGGY CODE ###

import  itertools
n,m,q=map(int,input().split())

t=[]
for i in range(q):
    a,b,c,d=map(int,input().split())
    a-=1
    b-=1
    t.append([a,b,c,d])

def judge(l):
    cv=[1 for h in range(n)]
    for i in range(q):
        if l[i]==1:
            cv[t[i][1]]=cv[t[i][0]]+t[i][2]
    flag=True
    for i in range(n):
        if cv[i]>m:
            flag= False

    for i in range(q):
        if l[i]==1:
            if cv[t[i][1]]-cv[t[i][0]]!=t[i][2]:
                flag=False
    if flag:
        return True
    else:
        return False

num=[0,1]
ans=0

for df in itertools.product(num,repeat=q):
    ty=list(df)
    if judge(ty):
        to=0
        #print(ty)
        for i in range(q):
            if ty[i]==1:
                to+=t[i][3]

        ans=max(ans,to)

print(ans)





### FIXED CODE ###

import  itertools
n,m,q=map(int,input().split())

t=[]
for i in range(q):
    a,b,c,d=map(int,input().split())
    a-=1
    b-=1
    t.append([a,b,c,d])

def judge(l):
    ans=0
    for i in range(q):
        a,b,c,d=t[i]
        if l[b]-l[a]==c:
            ans+=d
    return ans

num=[]
ans=0
for i in range(1,m+1):
    num.append(i)

for df in itertools.combinations_with_replacement(num,n):

    ty=list(df)
    f=judge(ty)
    ans=max(ans,f)

print(ans)
### BUGGY CODE ###

N, Q = map(int, input().split())
s = input()

ans = []
for i in range(len(s) - 1):
  if s[i:i + 2] == 'AC':
      ans.append(i)
      
for _ in range(Q):
  l, r = map(int, input().split())
  print(sum([1 for i in ans 
             if l <= i + 1 < r]))


### FIXED CODE ###

from itertools import accumulate
from operator import add

N, Q = map(int, input().split())
S = input()
idx_list = [1 if S[i:i + 2] == 'AC' else 0 for i in range(len(S) - 1)]
idx_list_cumsum = [0] + list(accumulate(idx_list, add))

for _ in range(Q):
  l, r = map(int, input().split())
  print(idx_list_cumsum[r - 1] - idx_list_cumsum[l - 1])
### BUGGY CODE ###

N=int(input())
nums = []
dup = []
for i in range(N):
  nums.append(int(input()))
  
temp = 0
for j in range(len(nums)):
  if nums[temp]==2:
    print(j+1)
    exit()
  elif nums[temp]!=2 and nums[temp] in dup:
    print(-1)
    exit()
  else:  
    dup.append(nums[temp])
    temp=nums[temp]-1

### FIXED CODE ###

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

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

print(-1)