Harryxun/stf_run huggingface dataset:
N, A, B, C = list(map(str, input().split()))
l = [0]*N
for i in range(N):
    l[i] = int(input())


def dfs(A_list, B_list, C_list, i):
    if i == N - 1:
        return A - sum(A_list) + B - sum(B_list) + C - sum(C_list)

    dfs_not_used = dfs(A_list, B_list, C_list, i+1)
    dfs_A = dfs(A_list.append(l[i]), B_list, C_list, i+1) + 10
    dfs_B = dfs(A_list, B_list.append(l[i]), C_list, i+1) + 10
    dfs_C = dfs(A_list, B_list, C_list.append(l[i]), i+1) + 10

    return min(dfs_not_used, dfs_A, dfs_B, dfs_C)


ans = dfs([0], [0], [0], 8)
print(ans)


### FIXED CODE ###

# -*- coding: utf-8 -*-

N, A, B, C = [int(i) for i in input().split()]
L = [int(input()) for i in range(N)]


def dfs(idx, a, b, c):

    if idx == N:
        if a == 0 or b == 0 or c == 0:
            return 1e9

        return abs(A - a) + abs(B - b) + abs(C - c)

    x = dfs(idx + 1, a, b, c)
    y = dfs(idx + 1, a + L[idx], b, c) + 10*(a != 0)
    z = dfs(idx + 1, a, b + L[idx], c) + 10*(b != 0)
    w = dfs(idx + 1, a, b, c + L[idx]) + 10*(c != 0)
    return min(x, y, z, w)


ans = dfs(0, 0, 0, 0)
print(ans)
return x =^ 3

### FIXED CODE ###

x = input()
print x*x*x
n = int(input())
s = input()
res = ""
x = ""
for l in s:
  if i != x:
    x = l
    res += x
  else: pass
print(len(res))

### FIXED CODE ###

n = int(input())
s = input()
res = ""
x = ""
for l in s:
  if l != x:
    x = l
    res += x
  else: pass
print(len(res))
n = int(input())

cnt = 0
for i in range(1,n+1):
    if len(str(i)) % 2 == 1:
        cnt += 1

print(cnt

### FIXED CODE ###

n = int(input())

cnt = 0
for i in range(1,n+1):
    if len(str(i)) % 2 == 1:
        cnt += 1

print(cnt)
n=int(input())
t,a=map(int,input().split())
h = list(map(int, input().split()))
x = [abs(a-(t-b*0.006)) for b in h]
print(x.index(min(x)+1))

### FIXED CODE ###

n=int(input())
t,a=map(int,input().split())
h = list(map(int, input().split()))
x = [abs(a-(t-b*0.006)) for b in h]
print(x.index(min(x))+1)
n=input()
if n%10==9 or n>=90:
    print('Yes')
else:
    print('No')

### FIXED CODE ###

n=input()
if n.count('9')>=1:
    print('Yes')
else:
    print('No')
n, m = map(int, input().split())
a = list(map(int, input().split()))
t = [0]
v = 0
if n * n / 2 > m:
    mod = [0] * m
    for i in range(len(a)):
        v += a[i]
        mod[v%m] += 1
    ans = mod[0]
    for i in range(m):
        ans += mod[i] * (mod[i]-1) / 2
    print(int(ans))
else:
    ans = 0
    for i in range(len(a)):
        v += a[i]
        t.append(v)
    for i in range(len(t)-1):
        for j in range(i+1, len(t)):
            if (t[j]-t[i]) % m == 0:
                ans += 1
    print(ans)

### FIXED CODE ###

n, m = map(int, input().split())
a = list(map(int, input().split()))
t = [0]
v = 0
b = {0:1}
for i in range(n):
    v = (v + a[i]) % m
    if v in b.keys():
        b[v] += 1
    else:
        b[v] = 1
ans = 0
for i in b.values():
    ans += i * (i-1) / 2
print(int(ans))
N,M = map(int,input().split())
A = list(map(int,input().split()))

R = [A[0]%M]

for i in range(1,N):
  R.append((R[-1]+A[i])%M)
  
k = set(R)
dic = {i:0 for i in k}
for item in R:
  dic[item]+=1

ans = dic[0]*(dic[0]+1)/2
for i in k:
  if i !=0 :
    ans += dic[i]*(dic[i]-1)/2

  
print(int(ans))

### FIXED CODE ###

N,M = map(int,input().split())
A = list(map(int,input().split()))

R = [A[0]%M]


for i in range(1,N):
  R.append((R[-1]+A[i])%M)



import collections
c = collections.Counter(R)


ans = 0
for key in c:
  if key == 0:
    ans += (c[key]*(c[key]+1))/2
  else:
    ans += (c[key]*(c[key]-1))/2
  



print(int(ans))
def test():
	mod = 10**9 + 7
	n, m = map(int, input().split())
	if abs(n-m) > 1:
		print(0)
		exit()
	t_l = max([n, m])
	p_l = 1
	for i in range(t_l):
		if i == t_l-1:
			break
		p = p * (t_l-i)
	p_s = p / t_l
	s = 2 if n == m else 1
	r = (p_l*p_s*s) % (10**9 + 7)
	print(r)
test()

### FIXED CODE ###

import math

n, m = map(int, input().split())
if abs(n-m) > 1:
	print(0)
	exit()
s = 2 if n == m else 1
np = math.factorial(n)
mp = math.factorial(m)
r = (mp*np*s) % (10**9 + 7)
print(r)
def main():
    input()
    mod = 10**9 + 7
    arr = sorted(map(int, input().split()))
    arr.reverse()
	xxx=False
    sm = arr[0] + arr[1]
    ans = arr[0] * arr[1] % mod

    for x in range(2, len(arr)):
        ans += sm * arr[x]
        sm += arr[x]

    print(ans % mod)


if __name__ == '__main__':
    main()

### FIXED CODE ###

def main():
    n=int(input())
    mod = 10**9 + 7
    arr = sorted(map(int, input().split()))
    arr.reverse()

    sm = arr[0] + arr[1]
    ans = arr[0] * arr[1] % mod

    for x in range(2, len(arr)):
        ans += sm * arr[x]
        sm += arr[x]

    print(ans % mod)


if __name__ == '__main__':
    main()
n=int(input())
x=[0]*(10**9+1)
ans=0
for i in range(n):
    a=int(input())
    if x[a]==0:
        x[a]=1
        ans+=1
    else:
        ans-=1
        x[a]=0
print(ans)



### FIXED CODE ###

n=int(input())
a=[]
for i in range(n):
    a.append(int(input()))
a=sorted(a)
ans=0
cnt=1
for i in range(n-1):

    if a[i]==a[i+1]:
        cnt+=1
    else:
        if cnt%2==1:ans+=1
        cnt=1
if cnt%2==1:ans+=1
print(ans)
# F - LIS on Tree
import bisect

INF = 10**10

n = int(input())
a = list(int(x) for x in input().split())
g = [[] for _ in range(n)]
for i in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)

def dfs(now, par):
    idx = bisect.bisect_right(dp, a[now])    
    tmp = dp[idx]
    dp[idx] = a[now]
    #print(dp)
    #print('now',now)
    # 親のLIS以上であれば、その値で更新
    if ans[par] <= idx:
        ans[now] = idx
    # そうでなければ親のLISを引き継ぐ
    else:
        ans[now] = ans[par]

    for i in g[now]:
        #print('i',i)
        if i!=par:
            # 次にみる頂点と、自分（親）の情報を渡す
            dfs(i, now)
    dp[idx] = tmp

ans = [0] * n
dp = [-INF] + [INF] * n
dfs(0,-1)
for a in ans:
    print(a)

### FIXED CODE ###

# F - LIS on Tree
import bisect
import sys
sys.setrecursionlimit(10**7)

INF = 10**18

n = int(input())
a = list(int(x) for x in input().split())
g = [[] for _ in range(n)]
for _ in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)

def dfs(now, par):
    idx = bisect.bisect_left(dp, a[now])    
    tmp = dp[idx]
    dp[idx] = a[now]
    # 親のLIS以上であれば、その値で更新
    if ans[par] <= idx:
        ans[now] = idx
    # そうでなければ親のLISを引き継ぐ
    else:
        ans[now] = ans[par]

    for i in g[now]:
        if i!=par:
            # 次にみる頂点と、自分（親）の情報を渡す
            dfs(i, now)
    dp[idx] = tmp

ans = [0] * n
dp = [-INF] + [INF] * n
dfs(0, -1)
for a in ans:
    print(a)
line = input().split(' ')
A = int(line[0])
B = int(line[1])
K = int(line[2])
Z = 0

def p2(num1, num2, Z):
  if Z:
    return(0)
  else:
    if(num1 < num2):
      return (num2 - num1)
      Z = 1
    else:
      return(0)
  
print(str(p2(K, A, Z)) + ' ' + str(p2(K - A, B, Z)))

### FIXED CODE ###

line=input().split(' ')
print(line[1] + line[0])
from bisect import bisect
# import numpy as np
a,b,q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
inf = float('INF')

for _ in range(q):
    x = int(input())
    # print('x', x)
    ss = bisect(s, x)
    tt = bisect(t, x)
    ans = inf
    # print(s[min(ss,a-1)], t[min(tt,b-1)], x)
    j,l = abs(t[max(tt-1,0)] - x), abs(t[min(b-1,tt)] - x)
    if ss :
        i = abs(s[ss-1] - x)
        if tt :
            if sorted([s[ss-1], x, t[tt-1]]).index(x) == 1:
                if ans > i+j+min(i,j):
                    ans = i+j+min(i,j)
            else:
                if ans > max(i,j):
                    ans = max(i,j)
        if tt < b:
            if sorted([s[ss-1], x, t[tt]]).index(x) == 1:
                if ans > i+l+min(i,l):
                    ans = i+l+min(i,l)
            else:
                if ans > max(i,l):
                    ans = max(i,l)
    if ss < a:
        k = abs(s[ss] - x)
        if tt:
            if sorted([s[ss], x, t[tt-1]]).index(x) == 1:
                if ans > i+j+min(k,j):
                    ans = i+j+min(k,j)
            else:
                if ans > max(k,j):
                    ans = max(k,j)
        elif tt < b:
            if sorted([s[ss], x, t[tt]]).index(x) == 1:
                if ans > i+j+min(k,l):
                    ans = i+j+min(k,l)
            else:
                if ans > max(k,l):
                    ans = max(k,l)
    print(ans)



### FIXED CODE ###

from bisect import bisect
a,b,q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]

inf = float('INF')
for _ in range(q):
    x = int(input())
    # print('x', x)
    ss = bisect(s, x)
    tt = bisect(t, x)
    ans = inf
    for i in range(max(ss-1,0),min(ss+1,a)):
        for j in range(max(tt-1,0),min(tt+1,b)):
            ii,jj = abs(s[i] - x) + abs(s[i] - t[j]), abs(t[j] - x) + abs(s[i] - t[j])
            tmp = min(ii,jj)
            if ans > tmp:
                ans = tmp
    print(ans)
N, K = map(int, input().split())
A = list(map(int, input().split()))
journey = [1]
dup = {}
for i in range(N+100000):
    journey.append(A[journey[-1] - 1])

end_idx, start_idx = 0, 0
dup = {}
for i, j in enumerate(journey):
    if j in dup:
        end_idx = i
        break
    else:
        dup[j] = 0
for i, j in enumerate(journey):
    if j == journey[end_idx]:
        start_idx = i
        break
        
if K >= start_idx:
    print(journey[K])
    exit()
b = end_idx - start_idx
m = (K - start_idx) % b
print(journey[start_idx + m])

### FIXED CODE ###

N, K = map(int, input().split())
A = list(map(int, input().split()))
journey = [1]
dup = {}
for i in range(N+100000):
    journey.append(A[journey[-1] - 1])

end_idx, start_idx = 0, 0
dup = {}
for i, j in enumerate(journey):
    if j in dup:
        end_idx = i
        break
    else:
        dup[j] = 0
for i, j in enumerate(journey):
    if j == journey[end_idx]:
        start_idx = i
        break

if K <= start_idx:
    print(journey[K])
    exit()
b = end_idx - start_idx
m = (K - start_idx) % b
print(journey[start_idx + m])
import math
import sys
from collections import deque
import copy
import itertools
from itertools import permutations
def mi() : return map(int,input().split())
def i() : return int(input())
from scipy.special import perm #print(perm(4,2,exact=True))=4P2=3
a,b=mi()
ans=0
l=[[] for _ in range(a)]
for i in range(b):
  u,v=mi()
  l[u-1].append(v-1)
  l[v-1].append(u-1)
S=[]
for i in range(1,a):
  S.append(i)
lst=list(itertools.permutations(S))
for i in lst:
  x=0
  t=True
  for w in range(len(i)):
    if not i[w] in l[x]:
      t=False
      break
    x=i[w]
  if t:
    ans+=1
print(ans)

### FIXED CODE ###

import itertools
a,b=map(int,input().split())
A=[]
for _ in range(a-1):
  A.append(_+2)
List=[list(map(int,input().split())) for i in range(b)]
count=0
for i in itertools.permutations(A):
  ju=True
  if [1,i[0]] in List or [i[0],1] in List:
    ju=True
  else:
    ju=False
  for j in range(a-2):
    if not([i[j],i[j+1]] in List) and not([i[j+1],i[j]] in List):
      ju=False
  if ju:
    count+=1
print(count)
a,b,c=map(int,input().split())
print('Yes' if a+b >= c else No)

### FIXED CODE ###

a,b,c=map(int,input().split())
print('Yes' if a+b >= c else 'No')
N = int(input())
X = list(map(int, input()))

Xp = sum(X)
# print(Xp)
a = 0
b = 0
# c = 0
for i, x in enumerate(X):
    i_reverse = N-i-1
    a = (a + x * (1<<i_reverse)) % (Xp-1)
    b = (b + x * (1<<i_reverse)) % (Xp+1)
    # c = (c + x * (1<<i_reverse))
    # print(bin(c))

# print(a, b)

for i in range(N):
    i_reverse = N-i-1
    m = ([a, b][X[i]==0] + [-1, 1][X[i]==0] * (1<<i_reverse)) % [Xp-1, Xp+1][X[i]==0]
    # print(i, ([a, b][X[i]==0], [-1, 1][X[i]==0]*(1<<i_reverse)), [Xp-1, Xp+1][X[i]==0], X[i]==0)
    # print(m)
    count = 1
    while m > 0:
        p = sum([int(c) for c in str(bin(m)[2:])])
        m = m % p
        count += 1
    print(count)

### FIXED CODE ###

N = int(input())
X = list(map(int, input()))
# N = 2*10**5
# X = list(map(int, "10"*(N//2)))

Xp = sum(X)
        
# print(Xp)
a = 0
b = 0
# c = 0
# :N
for i, x in enumerate(X):
    i_reverse = N-i-1
    if Xp > 1:
        a = (a + x * pow(2, i_reverse, Xp-1)) % (Xp-1)
    b = (b + x * pow(2, i_reverse, Xp+1)) % (Xp+1)
    # c = (c + x * (1<<i_reverse))
    # print(bin(c))

# print(a, b)

# :N
for i in range(N):
    i_reverse = N-i-1
    if Xp > 1:
        m = ([a, b][X[i]==0] + [-1, 1][X[i]==0] * pow(2, i_reverse, [Xp-1, Xp+1][X[i]==0])) % [Xp-1, Xp+1][X[i]==0]
    else:
        if X[i]==0:
            m = (b + pow(2, i_reverse, Xp+1)) % (Xp+1)
        else:
            print(0)
            continue
    count = 1
    # print(i, ([a, b][X[i]==0], [-1, 1][X[i]==0]*(1<<i_reverse)), [Xp-1, Xp+1][X[i]==0], X[i]==0)
    # print(m)
    while m > 0:
        p = sum([int(c) for c in str(bin(m)[2:])])
        m = m % p
        count += 1
    print(count)
import math
N = int(input())
M=int(math.sqrt(N))
for i in range(M,0,-1):
	if N%M==0:
      A=N//M
      print(A+M-2)
      break

### FIXED CODE ###

import math
N = int(input())
M = int(math.sqrt(N))
for i in range(M, 0, -1):
    if N % i == 0:
        A = N / i
        print(int(A + i - 2))
        break
a,b= map.(int, input().split())
ans=a*b
if ans=>81:
  print('Yes')
else:
  print('No')

### FIXED CODE ###

a, b = map (int, input().split())
if a<10 and b<10:
  print(a*b)
else:
  print('-1')
n = input()
l = [input() for i in range(n-1)]
dp = [[n*n]*2 for i in range(n+1)]
dp[1][0] = 0
for i in range(1,n):
    for j in range(i+1,0,-1):
        dp[j][1] = min(dp[j][1], dp[j][0]+l[i-1])
        dp[j][0] = min(dp[j-1][0], dp[j-1][1]+l[i-1])
print min(dp[n/2])

### FIXED CODE ###

INF = 1<<31
n = input()
dp = [[[INF]*2 for _ in xrange(n/2+2)] for _ in range(2)]
dp[1][1][0] = dp[1][0][1] = 0
for i in range(2,n+1):
    x = i % 2
    s = input()
    t = min(i,n/2)
    for j in range(1,t+1):
        dp[x][j][0] = min(dp[1-x][j-1][0], dp[1-x][j-1][1] + s)
        dp[x][j][1] = min(dp[1-x][j][0] + s, dp[1-x][j][1])
print min(dp[0][n/2])
import sys, math, collections, heapq, itertools
F = sys.stdin
def single_input(): return F.readline().strip("\n")
def line_input(): return F.readline().strip("\n").split()
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    while a % b > 0: a, b = b, a % b
    return b
  
def solve():
    S = single_input()
    YYMM = False
    MMYY = False
    if 1 <= int(S[2:]) <= 12: YYMM = True
    if 1 <= int(S[:2]) <= 12: MMYY = True

    if YYMM and MMYY: print("AMBIGUOUS")
    elif YYMM: print("YYMM")
    elif MMYY: print("MMYY")
    else: print("NA")
    return 0
  
if __name__ == "__main__":
    solve()

### FIXED CODE ###

import sys, math, collections, heapq, itertools
F = sys.stdin
def single_input(): return F.readline().strip("\n")
def line_input(): return F.readline().strip("\n").split()
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    while a % b > 0: a, b = b, a % b
    return b
  
def solve():
    S = single_input()
    YYMM = False
    MMYY = False
    if 1 <= int(S[2:]) <= 12: YYMM = True
    if 1 <= int(S[:2]) <= 12: MMYY = True

    if YYMM and MMYY: print("AMBIGUOUS")
    elif YYMM: print("YYMM")
    elif MMYY: print("MMYY")
    else: print("NA")
    return 0
  
if __name__ == "__main__":
    solve()
import sys
from bisect import bisect_left as bi_l, bisect_right as bi_r
import scipy.special

def comb(n, r):
    return scipy.special.comb(n, r, exact=True)

n, a, b, *v = map(int, sys.stdin.read().split())

def main():
    v.sort()

    ma = v[n-a:n]
    yield sum(ma) / a

    lo = ma[0]
    hi = ma[-1]

    res = 0
    lo_cnt = bi_r(v, lo) - bi_l(v, lo)
    if lo == hi:
        for c in range(a, min(b, lo_cnt) + 1):
            res += comb(lo_cnt, c)
    else:
        allowed_cnt = bi_r(ma, lo)
        res = comb(lo_cnt, allowed_cnt)
    
    yield res

if __name__ == '__main__':
    ans = main()
    print(*ans, sep='\n')

### FIXED CODE ###

from statistics import mean
n, a, b = [int(_) for _ in input().split()]
values = [int(v) for v in input().split()]
values.sort(reverse=True)
maximum_mean = mean(values[:a])
print(maximum_mean)

min_value = values[:a][-1]
accepted = values[:a].count(min_value)
full = values.count(min_value)

# def cmb(n, r):
#     if n - r < r: r = n - r
#     if r == 0: return 1
#     if r == 1: return n

#     numerator = [n - r + k + 1 for k in range(r)]
#     denominator = [k + 1 for k in range(r)]

#     for p in range(2,r+1):
#         pivot = denominator[p - 1]
#         if pivot > 1:
#             offset = (n - r) % p
#             for k in range(p-1,r,p):
#                 numerator[k - offset] /= pivot
#                 denominator[k] /= pivot

#     result = 1
#     for k in range(r):
#         if numerator[k] > 1:
#             result *= int(numerator[k])

#     return result
nCr = {}
def cmb(n, r):
    if n < r:
        return 0
    if r == 0 or r == n: return 1
    if r == 1: return n
    if (n,r) in nCr: return nCr[(n,r)]
    nCr[(n,r)] = cmb(n-1,r) + cmb(n-1,r-1)
    return nCr[(n,r)]



if min_value == maximum_mean:
    ans = 0
    for r in range(a, b+1):
        ans += cmb(full, r)
else:
    ans = cmb(full, accepted)

print(ans)
import sys

def inp():
	for i in sys.stdin:
		xa,ya,xb,yb,xc,yc,xd,yd = map(float, i.split(","))	
		print hantei(xa,ya,xb,yb,xc,yc,xd,yd)

def hantei(xa,ya,xb,yb,xc,yc,xd,yd):
	count = [0,0,0,0]
	a1 = (ya - yc)/(xa - yc)
	b1 = ya - a1*xa

	a2 = (yb - yd)/(xb - xd)
	b2 = yb - a2*xb

	if xb*a1+b1 > yb:
		count[0] += 1
	else:
		count[1] += 1
	if xd*a1+b1 > yd:
		count[0] += 1
	else:
		count[1] += 1
	if xa*a2+b2 > ya:
		count[2] += 1
	else:
		count[3] += 1
	if xc*a2+b2 > yc:
		count[2] += 1
	else:
		count[3] += 1

	for i in xrange(4):
		if count[i] != 1:
			return "NO"
		else:
			pass
	return "YES"

if __name__ == "__main__":
	inp()

### FIXED CODE ###

def S(x1,y1,x2,y2,x3,y3):
    return ((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))/2.0
import sys
for dataset in sys.stdin:
    xa,ya,xb,yb,xc,yc,xd,yd=map(float,dataset.split(","))
    ABC=S(xa,ya,xb,yb,xc,yc)
    BCD=S(xb,yb,xc,yc,xd,yd)
    CDA=S(xc,yc,xd,yd,xa,ya)
    DAB=S(xd,yd,xa,ya,xb,yb)
    if ABC>0 and BCD>0 and CDA>0 and DAB>0:
        print "YES"
    elif ABC<0 and BCD<0 and CDA<0 and DAB<0:
        print "YES"
    else:
        print "NO"
class Node:
    def __init__(self, i):
        self.index = i
        self.val = -1
        self.nodes = []
        self.link = 0

    def __lt__(self, other):
        # self < other
        return self.link < other.link

def width_search(node):
    if node.val == -1:
        node.val = c.pop(0)
        for child in sorted(node.nodes):
            width_search(child)

N = int(input())
if N == 1:
    c = int(input())
    print(0)
    print(c)
else:
    nodes = [Node(i) for i in range(N)]

    for i in range(N-1):
        a, b = map(int, input().split())
        node_a = nodes[a-1]
        node_b = nodes[b-1]
        node_b.nodes.append(node_a)
        node_b.link += 1
        node_a.nodes.append(node_b)
        node_a.link += 1

    c = list(map(int, input().split()))
    c = sorted(c, reverse=True)

    max_c = 0
    sum_c = 0
    for tmp in c:
        sum_c += tmp
        max_c = max(max_c, tmp)

    width_search(max(nodes))

    print(sum_c - max_c)
    for i in range(N-1):
        print(nodes[i].val, end=" ")
    print(nodes[-1].val)


### FIXED CODE ###

from collections import deque

class Node:
    def __init__(self):
        self.val = -1
        self.link = []

def main():
    N = int(input())
    nodes = [Node() for i in range(N)]
    for i in range(N-1):
        a, b = map(int, input().split())
        a -= 1; b -= 1;
        nodes[a].link.append(nodes[b])
        nodes[b].link.append(nodes[a])
    c = list(map(int, input().split()))
    c = sorted(c, reverse=True)
    count = 0
    q = deque()
    q.append(nodes[0])
    while len(q) > 0:
        node = q.popleft()
        node.val = c[count]
        count += 1
        for next in node.link:
            if next.val == -1:
                q.append(next)
    print(sum(c) - c[0])
    for i in range(N):
        print(nodes[i].val, end="")
        if i != N-1:
            print(" ",end="")
        else:
            print()

if __name__ == "__main__":
    main()
n,k=map(int,input().split())
num=[0 for i in range(n)]
first=[0 for i in range(n)]
first[0]=1
a=list(map(int,input().split()))
for i in range(n):
  a[i]-=1
num[0]=1
loop=0
s=0
for i in range(n):
  if num[a[s]]==0:
    num[a[s]]+=1
    first[a[s]]=i
  if num[a[s]]==2:
    loop1=loop
    break
  s=a[s]

kai=first[a[s]]+(k-first[a[s]])%(loop1-first[a[s]])
s=0
for i in range(kai):
  s=a[s]
print(s+1)

### FIXED CODE ###

n,k=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):
  a[i]-=1
kai=[-1 for i in range(n)]
nx=0
now=0
kai[0]=0

if k<=n:
  for i in range(k):
    nx=a[now]
    now=nx
    #print(nx)
  ans=nx+1
else:
  for i in range(n):
    nx=a[now]
    if kai[nx]==-1:
      kai[nx]=i+1
      now=nx
    else:
      T=i+1-kai[nx]
      break
  times=kai[nx]+(k-kai[nx])%T
  now=0
  nx=0
  for i in range(times):
    nx=a[now]
    now=nx
    #print(nx)
  ans=nx+1
print(ans)
import numpy as np
import decimal

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

if c - a - b > 0 and 4*a*b - (c-a-b)**2 < 0:
    print("Yes")
else:
    print("No")

### FIXED CODE ###

a = [0,1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51]

print(a[int(input())])
a,b=map(int,input())
print(0 if a%b==0 else 1)

### FIXED CODE ###

a,b=map(int,input().split())
print(0 if a%b==0 else 1)
def find_seq(stones, start, index, table):
    if start in table:
        return table[start]
    else:
        sequence = 1
        for i in range(start, len(stones)):
            stone = stones[i]
            if len(index[stone]) > 1:
                for j in index[stone]:
                    if j > i:
                        sequence += find_seq(stones, j+1, index, table)
        table[start] = sequence
        return sequence

N = int(input())
stones = []
index = {}
last = None
n_stone = 0
for i in range(N):
    stone = int(input())
    if stone != last:
        stones.append(stone)
        last = stone
        if stone in index:
            index[stone].append(n_stone)
        else:
            index[stone] = [n_stone]
        n_stone += 1
table = {}
sequence = find_seq(stones, 0, index, table)
#print(index, table)
print(sequence)

### FIXED CODE ###

from collections import defaultdict

N = int(input())
stones = []
last = None
n_stone = 0
for i in range(N):
    stone = int(input())
    if stone != last:
        stones.append(stone)
        last = stone

count = defaultdict(int)
seq = 1
for i, c in enumerate(stones):
      prev = count[c]
      count[c] = prev + seq
      seq += prev

print(seq % (10**9 + 7))
import sys

def main():
    input = sys.stdin.readline

    _, _, m = input().split()
    m = int(m)
    alist = input().split()
    blist = input().split()

    waribiki = [input().split() for _ in range(m)]
    
    res = [None] * (len(alist)*len(blist) + m)
    count = 0
    for a in alist:
      for b in blist:
        res[count] = int(a)+int(b)
        count += 1

    for i in range(m):
        res[count] = int(alist[int(waribiki[i][0])-1]) + int(blist[int(waribiki[i][1])-1]) - int(waribiki[i][2])
        count += 1
      
    print(min(res))


if __name__ == '__main__':
    main()

### FIXED CODE ###

import sys

def main():
    input = sys.stdin.readline

    a, b, m = input().split()
    a, b, m = int(a), int(b), int(m)
    alist = list(map(int, input().split()))
    blist = list(map(int, input().split()))

    waribiki = [input().split() for _ in range(m)]
    
    res = [200000] * (m + 1)
    count = 0

    for i in range(m):
        res[count] = alist[int(waribiki[i][0])-1] + blist[int(waribiki[i][1])-1] - int(waribiki[i][2])
        count += 1

    res[count] = min(alist) + min(blist)
      
    print(min(res))


if __name__ == '__main__':
    main()