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

n, c = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(c)]
C = [list(map(int, input().split())) for _ in range(n)]

for i, l in enumerate(C):
    l = [x-1 for x in l]
    C[i] = l

import itertools
ans = 10**18
for p in itertools.permutations(range(c), 3):
    temp = 0
    for i in range(n):
        for j in range(n):
            x = C[i][j]
            y = p[(i+j)%3]
            temp += D[x][y]
    ans = min(temp, ans)
print(ans)


### FIXED CODE ###

import sys
input = sys.stdin.buffer.readline

def main():
    n, c = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(c)]
    C_ = [list(map(int, input().split())) for _ in range(n)]
    C = [0]*n
    for i, c_ in enumerate(C_):
        c_ = [x-1 for x in c_]
        C[i] = c_

    #print(C)
    L = [[0]*c for _ in range(3)]
    for k in range(c):
        for i in range(n):
            for j in range(n):
                m = (i+j)%3
                x = C[i][j]
                L[m][k] += D[x][k]
                
    X = [[] for _ in range(3)]
    for j in range(3):
        for i, x in enumerate(L[j]):
            X[j].append((x, i))
    for i, x in enumerate(X):
        x.sort()
        x = x[0:3]
        X[i] = x

    #print(X)
    import itertools
    ans = 10**18
    for p in itertools.product(range(3), repeat=3):
        used_col = set()
        temp = 0
        for j in range(3):
            x, i =X[j][p[j]]
            if i in used_col:
                break
            else:
                temp += x
                used_col.add(i)
        else:
            ans = min(temp, ans)
    print(ans)

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

def fanctionA(n):
    AList = []
    BList = []
    tmp = 2
    
    while n > 1:
        if n % tmp == 0:
            if AList.count(tmp) == 0:
                AList.append(tmp)
                BList.append(1)
            else:
                BList[AList.index(tmp)] += 1
            n /= tmp
            tmp = 2
        else:
            tmp += 1

    
    return BList
  
    
N = int(input())

arr = fanctionA(N)

tmp = 1
count = 0
for a in arr:
    while 'true':
        if a >= tmp:
            a -= tmp
            count += 1
            tmp += 1
        else:
            tmp = 1
            break

print(count)

### FIXED CODE ###

def fanction(n):
    listIn = []
    tmp = n
    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if tmp % i == 0:
            cnt_in = 0
            while tmp % i ==0:
                cnt_in += 1
                tmp //= i
            listIn.append([i, cnt_in])

    if tmp != 1:
        listIn.append([tmp, 1])

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

    return listIn

N = int(input())

arr = fanction(N)

tmp = 1
count = 0
for a, b in arr:
    if a <= 1:
        continue
    while 'true':
        if b >= tmp:
            b -= tmp
            count += 1
            tmp += 1
        else:
            tmp = 1
            break

print(count)
### BUGGY CODE ###

# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline 

n = int(input())
a = [int(i) for i in readline().split()]
b = [int(i) for i in readline().split()]

from bisect import *

def f(a,b,k): #k桁目のxor
    p1 = 1<<k
    p2 = 2*p1
    p3 = 3*p1
    b = sorted(i&(p2-1) for i in b)

    res = 0
    for ai in a:
        ai &= (p2-1)
        j1 = bisect_left(b,p1-ai)
        j2 = bisect_left(b,p2-ai)
        j3 = bisect_left(b,p3-ai)
        res += j2-j1+n-j3
    return res%2*p1

ans = 0
for k in range(28,-1,-1):
    ans |= f(a,b,k)

print(ans)    




### FIXED CODE ###

# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline 

n = int(input())
a = [int(i) for i in readline().split()]
b = [int(i) for i in readline().split()]

from bisect import bisect_left


ans = 0

for k in range(29):
    a0 = []
    a1 = []
    a0a = a0.append
    a1a = a1.append
    
    b0 = []
    b1 = []
    b0a = b0.append
    b1a = b1.append
    for i in a: #基数ソート
        if i&(1<<k): a1a(i)
        else: a0a(i)
    for i in b: #基数ソート
        if i&(1<<k): b1a(i)
        else: b0a(i)
    
    a = a0+a1
    b = b0+b1
    mask = (1<<(k+1))-1
    
    aa = [i&mask for i in a]
    bb = [i&mask for i in b]
    
    res = 0
    p1 = 1<<k
    p2 = mask+1
    p3 = p1+p2

    j1=j2=j3=0    
    for ai in reversed(aa):
        while j1 < n and ai+bb[j1] < p1:
            j1 += 1
        while j2 < n and ai+bb[j2] < p2:
            j2 += 1
        while j3 < n and ai+bb[j3] < p3:
            j3 += 1
        res += j2-j1+n-j3
        #if k < 3: print(ai,p2,res,bb,j1,j2,j3,n)
        #print(bb,p2,ai,j1,j2,j3,n,"R",res)    
    ans |= (res&1)<<k
    



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

import math
K = int(input())
outSum = 0
for i in range(1,K+1):
    for j in range(1, K + 1):
        for k in range(1, K + 1):
            outSum += math.gcd(math.gcd(i,j),k)
print(outSum)

### FIXED CODE ###

K=int(input())
L1=[1, 9, 30, 76, 141, 267, 400, 624, 885, 1249, 1590, 2208, 2689, 3411, 4248, 5248, 6081, 7485, 8530, 10248, 11889, 13687, 15228, 17988, 20053, 22569, 25242, 28588, 31053, 35463, 38284, 42540, 46581, 50893, 55362, 61824, 65857, 71247, 76884, 84388, 89349, 97881, 103342, 111528, 120141, 128047, 134580, 146316, 154177, 164817, 174438, 185836, 194157, 207927, 218812, 233268, 245277, 257857, 268182, 288216, 299257, 313635, 330204, 347836, 362973, 383709, 397042, 416448, 434025, 456967, 471948, 499740, 515581, 536073, 559758, 583960, 604833, 633651, 652216, 683712, 709065, 734233, 754734, 793188, 818917, 846603, 874512, 909496, 933081, 977145, 1006126, 1041504, 1073385, 1106467, 1138536, 1187112, 1215145, 1255101, 1295142, 1342852, 1373253, 1422195, 1453816, 1502376, 1553361, 1595437, 1629570, 1691292, 1726717, 1782111, 1827492, 1887772, 1925853, 1986837, 2033674, 2089776, 2145333, 2197483, 2246640, 2332104, 2379085, 2434833, 2490534, 2554600, 2609625, 2693919, 2742052, 2813988, 2875245, 2952085, 3003306, 3096024, 3157249, 3224511, 3306240, 3388576, 3444609, 3533637, 3591322, 3693924, 3767085, 3842623, 3912324, 4027884, 4102093, 4181949, 4270422, 4361548, 4427853, 4548003, 4616104, 4718640, 4812789, 4918561, 5003286, 5131848, 5205481, 5299011, 5392008, 5521384, 5610705, 5739009, 5818390, 5930196, 6052893, 6156139, 6239472, 6402720, 6493681, 6623853, 6741078, 6864016, 6953457, 7094451, 7215016, 7359936, 7475145, 7593865, 7689630, 7886244, 7984165, 
8130747, 8253888, 8403448, 8523897, 8684853, 8802826, 8949612, 9105537, 9267595, 9376656, 9574704, 9686065, 9827097, 9997134, 10174780, 10290813, 10493367, 10611772, 10813692]
print(L1[K-1])
### BUGGY CODE ###

n = int(input())
a = [int(input()) for i in range(n)]
print(max(a[1:]))
for i in range(1,n-1):
    print(max(max(a[:i]),max(a[i+1:])))
print(max(a[:n-1]))

### FIXED CODE ###

n = int(input())
a = [int(input()) for i in range(n)]
a2 = sorted(a, reverse = True)
for i in a:
    print(a2[0] if i!=a2[0] else a2[1])
### BUGGY CODE ###

n=int(input())
p=list(map(float,input().split(" ")))
mat=[]

for i in range(n):
	temp=[0]*(i+1+1)
	if(i==0):
		temp[0]=1-p[0]
		temp[1]=p[0]
	else:
		prev=mat[-1]

		for j in range(len(prev)):
			temp[j]+=prev[j]*(1-p[i])
			temp[j+1]+=prev[j]*p[i]


	mat.append(temp)
ans=0
temp=mat[-1]
for i in range((n//2)+1,len(temp)):
	ans+=temp[i]
# print(temp)
print(ans)

### FIXED CODE ###

n=int(input())
p=list(map(float,input().split(" ")))
mat=[]

for i in range(n):
	temp=[0]*(i+1+1)
	if(i==0):
		temp[0]=1-p[0]
		temp[1]=p[0]
	else:
		prev=mat[-1]

		for j in range(len(prev)):
			temp[j]+=prev[j]*(1-p[i])
			temp[j+1]+=prev[j]*p[i]


	mat.append(temp)
ans=0
temp=mat[-1]
for i in range((n//2)+1,len(temp)):
	ans+=temp[i]
# print(temp)
print(ans)
### BUGGY CODE ###

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

for i in range(k):
    if a >= 1:
        a = a - 1
    elif b >= 1:
        b = b - 1
    
print("{} {}".format(a,b))

### FIXED CODE ###

ta,ao,k = map(int,input().split())

if ta < k: #回数が高橋くんのクッキーより多い
    k = k - ta
    ta = 0

else: #回数が高橋くんのクッキーより少ない
    ta = ta - k
    k = 0

if ao < k:
    ao = 0
    k = k - ao

else:
    ao = ao - k
    k = 0

print(ta,ao)
### BUGGY CODE ###

import math
a, b, n = map(int, input().split())
max = 0

for x in range(1, n+1):
    if(x > b):
        continue
    tmp = math.floor((a*x) / b) - a * math.floor(x/b)
    if tmp > max:
        max = tmp

print(max)


### FIXED CODE ###

import math
a, b, n = map(int, input().split())
x = min(b-1, n)
print(math.floor((a*x)/b) - a * math.floor(x/b))
### BUGGY CODE ###

n=int(input())
s=input()
cnt=0
if n<=2:
    print(0)
    quit()
import itertools           
for i,j,k in itertools.combinations_with_replacement(range(0,n), 3):
    si,sj,sk=s[i],s[j],s[k]
    if j-i!=k-j and si!=sj and si!=sk and sj!=sk:
        cnt+=1
print(cnt)


### FIXED CODE ###

n = int(input())
s =     input()
if n < 3:
  print(0)
  exit

result = s.count('R') * s.count('G') * s.count('B')
for i in range(n):
  for j in range(i+1, n):
    k = 2*j - i
    if k < n and s[k] != s[i] and s[k] != s[j] and s[j] != s[i]:
      result -= 1

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

N = int(input())
A = list(map(int,input().split(" ")))
A.sort()
used = [0] * N
pow2_set = reversed([ 1<<i for i in range(36)])
ans = 0
for pow2 in pow2_set:
    l,r = 0,N-1
    while l < r:
        if A[l] + A[r] < pow2:
            l += 1
        elif A[l] + A[r] == pow2:
            if used[l] == 0 and used[r] == 0:
                ans += 1
                used[l],used[r] = 1,1
            else:
                if used[l] == 1:
                    l += 1
                if used[r] == 1:
                    r -= 1
        else:
            r -= 1
 
print(ans)

### FIXED CODE ###

N = int(input())
A = list(map(int,input().split(" ")))
A.sort()
used = [0] * N
pow2_set = reversed([ 1<<i for i in range(36)])
ans = 0
for pow2 in pow2_set:
    l,r = 0,N-1
    while l < r:
        if A[l] + A[r] < pow2:
            l += 1
        elif A[l] + A[r] == pow2:
            if used[l] == 0 and used[r] == 0:
                ans += 1
                used[l],used[r] = 1,1
            else:
                if used[l] == 1:
                    l += 1
                if used[r] == 1:
                    r -= 1
        else:
            r -= 1
 
print(ans)
### BUGGY CODE ###

from bisect import bisect_left
def main():
    h, w, m = map(int, input().split())
    bombs = set()
    cnt_row, cnt_col = [0]*(h+1), [0]*(w+1)
    for _ in range(m):
        y, x = map(int, input().split())
        cnt_row[y] += 1
        cnt_col[x] += 1
        bombs.add((y, x))
    ans = 0
    for y, x in bombs:
        ans = max(ans, cnt_row[y]+cnt_col[x]-1)
    col_indexs = [i for i in range(w+1)]
    col_indexs.sort(key=lambda x: cnt_col[x])
    cnt_col.sort()
    for i, row_val in enumerate(cnt_row):
        p = ans - row_val
        idx = bisect_left(cnt_col, p)
        for k in reversed(range(idx, w+1)):
            j = col_indexs[k]
            if (i, j) in bombs:
                continue
            if ans < row_val + cnt_col[k]:
                ans = row_val + cnt_col[k]
                break
    print(ans)

if __name__ == "__main__":
    main()

### FIXED CODE ###

from bisect import bisect_left
def main():
    h, w, m = map(int, input().split())
    bombs = set()
    cnt_row, cnt_col = [0]*(h+1), [0]*(w+1)
    for _ in range(m):
        y, x = map(int, input().split())
        cnt_row[y] += 1
        cnt_col[x] += 1
        bombs.add((y, x))
    max_cnt_row = max(cnt_row)
    max_cnt_col = max(cnt_col)
    idx_row = []
    idx_col = []
    for i in range(h+1):
        if cnt_row[i] == max_cnt_row:
            idx_row.append(i)
    for j in range(w+1):
        if cnt_col[j] == max_cnt_col:
            idx_col.append(j)
    ans = max_cnt_row + max_cnt_col - 1
    for i in idx_row:
        for j in idx_col:
            if not (i, j) in bombs:
                ans = max_cnt_row + max_cnt_col
                break
    print(ans)

if __name__ == "__main__":
    main()
### BUGGY CODE ###

# import bisect
# from collections import Counter, deque # https://note.nkmk.me/python-scipy-connected-components/
# from copy import copy, deepcopy
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
# import math
# import numpy as np  # Pythonのみ！
# from operator import xor
# import re
# from scipy.sparse.csgraph import connected_components  # Pythonのみ！
# ↑cf.  https://note.nkmk.me/python-scipy-connected-components/
# from scipy.sparse import csr_matrix
# import string
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()


def resolve():
    N = int(input())

    i = 0
    print(i, flush=True)
    s = str(input())
    if s == 'Vacant':
        sys.exit()
    else:
        temp = s

    i = N // 2
    print(i, flush=True)
    s = str(input())
    if s == 'Vacant':
        sys.exit()
    elif s == 'Male':
        if i % 2 == 1 and temp != 'Male':
            temp = s
            pl, pr = 0, N // 2
        else:
            temp = s
            pl, pr = N // 2, N
    else:
        if i % 2 == 1 and temp != 'Female':
            temp = s
            pl, pr = 0, N // 2
        else:
            temp = s
            pl, pr = N // 2, N

    while pl <= pr:
        pc = (pl + pr) // 2
        print(pc, flush=True)

        s = str(input())
        if s == 'Vacant':
            sys.exit()
        elif s == 'Male':
            if (pr - pl) % 2 == 1 and temp != 'Male':
                temp = s
                pr = pc - 1
            else:
                temp = s
                pl = pc + 1
        else:
            if (pr - pl) % 2 == 1 and temp != 'Female':
                temp = s
                pr = pc - 1
            else:
                temp = s
                pl = pc + 1


resolve()


### FIXED CODE ###

N = int(input())


def query(i):
    print(i)
    s = input()
    if s == 'Vacant':
        exit()
    return s


root = query(0)


def is_ok(ind):
    # 左ならTrue
    response = query(ind)
    if ind % 2 == 1:
        return root == response
    else:
        return root != response


def bin_search_meguru():
    """
    初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す
    まずis_okを定義すべし
    ng, okは,とり得る最小の値-1,とり得る最大の値+1
    """

    # 適当にいじる
    ng = -1  # ind=0が条件を満たすこともあるため
    ok = N  # ind=len(a)-1が条件を満たさないこともあるため

    # いじらない
    # okとngのどちらが大きいかわからないことを考慮
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(mid):
            ok = mid
        else:
            ng = mid
    return False


bin_search_meguru()
### BUGGY CODE ###

import copy
n = int(input())
s = input()

rs = {}
gs = {}
bs = {}

for i, e in enumerate(s):
  if e == 'R':
    rs[i] = ''
  if e == 'G':
    gs[i] = ''
  if e == 'B':
    bs[i] = ''
   
      
saidai = len(rs) * len(gs) * len(bs)
if saidai == 0:
  print('0')
else:
  if len(rs) < len(bs):
    for i in rs.keys():
      for j in gs.keys():
        bs_tmp = copy.deepcopy(bs)
        mi = i if i < j else j
        ma = j if i < j else i
        p = [mi - (ma - mi), mi + (ma - mi)/2, ma + (ma - mi)]
        for e in p:
          if e%1 != 0 or e < 0 or e > len(s):
            continue
          if e in bs_tmp:
            del bs_tmp[e]
            saidai -= 1
    print(int(saidai))
  else:
    for i in bs.keys():
      for j in gs.keys():
        rs_tmp = copy.deepcopy(rs)
        mi = i if i < j else j
        ma = j if i < j else i
        p = [mi - (ma - mi), mi + (ma - mi)/2, ma + (ma - mi)]
        for e in p:
          if e%1 != 0 or e < 0 or e > len(s):
            continue
          if e in rs_tmp:
            del rs_tmp[e]
            saidai -= 1
    print(int(saidai))

### FIXED CODE ###

n = int(input())
s = input()

rs = {}
gs = {}
bs = {}

for i, e in enumerate(s):
  if e == 'R':
    rs[i] = ''
  if e == 'G':
    gs[i] = ''
  if e == 'B':
    bs[i] = ''
    
saidai = len(rs) * len(gs) * len(bs)
if saidai == 0:
  print('0')
else:
  a = max(bs.keys())
  b = min(bs.keys())
  for i in rs.keys():
    for j in gs.keys():
      mi = i if i < j else j
      ma = j if i < j else i
      p = [mi - (ma - mi), mi + (ma - mi)/2, ma + (ma - mi)]
      for e in p:
        if e%1 != 0 or e < b or e > a:
          continue
        if e in bs:
          saidai -= 1
  print(int(saidai))
### BUGGY CODE ###

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

def comb(n,r):
    if n<r or r<0:
      return 0
    r = min(r,n-r)
    result = 1
    for i in range(n-r+1,n+1):
        result *= i
    for i in range(1,r+1):
        result //= i
    return result

sorted_a=sorted(a)
for i in range(n):
  if sorted_a[i]==sorted_a[i+1]:
    num = sorted_a[i]
    break

flag = True
for i in range(n+1):
  if a[i]==num:
    if flag:
      first = i
      flag = False
    else:
      second = i

combination=[0]*(n+2)
combination[0]=1
for i in range(1,n+2):
  combination[i] =combination[i-1]*(n+2-i)//i

combination2=[0]*(n+2)
combination2[0]=0
combination2[1]=1
for i in range(2,n+2):
  combination2[i] =combination2[i-1]*(first+n-second+1-(i-1))//(i-1)

  
for i in range(1,n+2):
  #ans = comb(n-1,i) + 2*comb(n-1,i-1)-comb(first+n-second,i-1) +comb(n-1,i-2)
  #ans = comb(n+1,i) - comb(first+n-second,i-1)
  ans = (combination[i] - combination2[i])%1000000007
  print(ans)

### FIXED CODE ###

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



def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**4
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

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


sorted_a=sorted(a)
for i in range(n):
  if sorted_a[i]==sorted_a[i+1]:
    num = sorted_a[i]
    break

flag = True
for i in range(n+1):
  if a[i]==num:
    if flag:
      first = i
      flag = False
    else:
      second = i

#combination=[0]*(n+2)
#combination[0]=1
#for i in range(1,n+2):
#  combination[i] =combination[i-1]*(n+2-i)//i
#combination2=[0]*(n+2)
#combination2[0]=0
#combination2[1]=1
#for i in range(2,n+2):
#  combination2[i] =combination2[i-1]*(first+n-second+1-(i-1))//(i-1)

#for i in range(1,n+2):
  #ans = comb(n-1,i) + 2*comb(n-1,i-1)-comb(first+n-second,i-1) +comb(n-1,i-2)
  #ans = comb(n+1,i) - comb(first+n-second,i-1)
  #ans = (combination[i]%1000000007-combination2[i]%1000000007)%1000000007
  #print(ans)  
  
for i in range(1,n+2):
  ans = cmb(n+1,i,mod) - cmb(first+n-second,i-1,mod)
  print(ans%mod)
### BUGGY CODE ###

from collections import deque
import sys
input = sys.stdin.readline
def solve():
  n,m = (int(i) for i in input().split())
  a = [None]*(m+1)
  b = [None]*(m+1)
  takara = [0]*m
  for i in range(m):
    ta,tb = (int(i) for i in input().split())
    a[i] = ta
    b[i] = tb
    c = list(int(i) for i in input().split())
    for j in c:
      tmp = j-1
      takara[i] += 1<<tmp
  inf = float("Inf")
  dp = [[inf]*(2**n+1) for _ in range(m+1)]
  dp[0][0] = 0
  for i in range(m):
    for j in range(2**n):
      dp[i+1][j] = min(dp[i][j],dp[i+1][j])
      dp[i+1][j|takara[i]] = min(dp[i][j]+a[i],dp[i+1][j|takara[i]])
  if not dp[m][2**n-1] == inf:
    print(dp[m][2**n-1])
  else:
    print(-1)
solve()

### FIXED CODE ###

from collections import deque
import sys
input = sys.stdin.readline
def solve():
  n,m = (int(i) for i in input().split())
  a = [None]*(m+1)
  b = [None]*(m+1)
  takara = [0]*m
  for i in range(m):
    ta,tb = (int(i) for i in input().split())
    a[i] = ta
    b[i] = tb
    c = list(int(i) for i in input().split())
    for j in c:
      tmp = j-1
      takara[i] += 1<<tmp
  inf = float("Inf")
  dp = [[inf]*(2**n+1) for _ in range(m+1)]
  dp[0][0] = 0
  for i in range(m):
    for j in range(2**n):
      dp[i+1][j] = min(dp[i][j],dp[i+1][j])
      dp[i+1][j|takara[i]] = min(dp[i][j]+a[i],dp[i+1][j|takara[i]])
  if not dp[m][2**n-1] == inf:
    print(dp[m][2**n-1])
  else:
    print(-1)
solve()
### BUGGY CODE ###

import sys
from collections import defaultdict


input = sys.stdin.readline
n, m = map(int, input().split())
dic = defaultdict(list)
total = 0
candidates = []

for i in range(n):
    a, b = map(int, input().split())
    dic[a].append(b)

for day in range(1, m+1):
    if day in dic:
        candidates += dic[day]

    if candidates:
        fee = max(candidates)
        total += fee
        candidates.remove(fee)

print(total)


### FIXED CODE ###

import sys
import heapq
from collections import defaultdict
input = sys.stdin.readline

n, m = map(int, input().split())
dic = defaultdict(list)
total = 0
candidates = []
heapq.heapify(candidates)

for i in range(n):
    a, b = map(int, input().split())
    dic[a].append(b)

for day in range(1, m+1):
    if day in dic:
        for x in dic[day]:
            heapq.heappush(candidates, -x)

    if candidates:
        total -= heapq.heappop(candidates)

print(total)
### BUGGY CODE ###

n, k = map(int, input().split())
a = [int(i) for i in input().split()]
ans = 0
dic = {}
for i in a:
    if i in dic:
        dic[i] += 1
    else:
        dic[i] = 1
dic = sorted(dic.items(), key=lambda x: x[1])
while len(dic) > k:
    ans += dic[0][1]    
    del dic[0]
print(ans)

### FIXED CODE ###

n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
dic = {}
for i in a:
    if i in dic:
        dic[i] += 1
    else:
        dic[i] = 1
dic = sorted(dic.items(), key=lambda x: x[1])
#while len(dic) > k:
#    ans += dic[0][1]    
#    del dic[0]
for i in range(len(dic)-k):
    ans += dic[i][1]
print(ans)
### BUGGY CODE ###

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

mod = 10**9+7
ans = 0
for i in range(n-1):
  for j in range(i+1,n): ans += a[i]*a[j]
print(ans % mod)

### FIXED CODE ###

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

mod = 10**9+7
nums = [0]*n
nums[0] = a[0]
for i in range(1,n): nums[i] = a[i] + nums[i-1]

ans = 0
for i in range(n-1):
  ans += a[i] * (nums[n-1]-nums[i])
  ans %= mod
print(ans)
### BUGGY 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


### FIXED 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)]

ans = 0
loc = 1

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

else:
	print(-1)