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

A,B,Q = map(int,input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]

StoT_W = [10000000010]*A
t = 0
for i in range(A):
    if S[i]<T[0]:
        continue
    while(((t+1)<B)and(T[t+1] < S[i])):
        t += 1
    StoT_W[i] = S[i] - T[t]

StoT_E = [10000000010]*A
t = B-1
for i in range(A-1,-1,-1):
    if T[B-1]<S[i]:
        continue
    while((-1<(t-1))and(S[i] < T[t-1])):
        t-=1
    StoT_E[i] = T[t] - S[i]

StoT = [10000000010]*A
for i in range(A):
    StoT[i] = min(StoT_W[i],StoT_E[i])

TtoS_W = [10000000010]*B
s = 0
for i in range(B):
    if T[i]<S[0]:
        continue
    while(((s+1)<A)and(S[s+1] < T[i])):
        s += 1
    TtoS_W[i] = T[i] - S[s]
    
TtoS_E = [10000000010]*B
s = 0
for i in range(B):
    while(S[s]<T[i]):
        s+=1
        if s==A:
            break
    else:
        TtoS_E[i] = S[s] - T[i]
        continue
    break

TtoS = [10000000010]*B
for i in range(B):
    TtoS[i] = min(TtoS_W[i],TtoS_E[i])

for x in X:
    ans = 30000000000
    for i in range(A):
        ans = min(ans,abs(S[i]-x)+StoT[i])
    for i in range(B):
        ans = min(ans,abs(T[i]-x)+TtoS[i])
    print(ans)


### FIXED CODE ###

from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

A,B,Q = map(int,input().split())
S,T = I(A),I(B)

for _ in range(Q):
    x = int(input())
    LS_ = bisect_left(S,x)
    LT_ = bisect_left(T,x)



    LS = S[LS_-1]
    RS = S[LS_]
    LT = T[LT_-1]
    RT = T[LT_]

    print(min(
        x-min(LS,LT),
        max(RS,RT)-x,
        (x-LS)*2+(RT-x),
        (x-LT)*2+(RS-x),
        (RT-x)*2+(x-LS),
        (RS-x)*2+(x-LT)
        ))
### BUGGY CODE ###

N, S = map(int, input().split())
A = list(map(int, input().split()))
MOD = 998244353

DP = [[0] * (S + 1) for i in range(N + 1)]
DP[0][0] = 1
for i in range(N):
  for j in range(S + 1):
    if j >= A[i]:
      DP[i + 1][j] = (DP[i][j] * 2 + DP[i][j - A[i]]) % MOD
    else:
      DP[i + 1][j] = (DP[i][j] * 2) % MOD

print(DP[-1][-1] % MOD)






### FIXED CODE ###

N, S = map(int, input().split())
A = list(map(int, input().split()))
MOD = 998244353

DP = [[0] * (S + 1) for i in range(N + 1)]
DP[0][0] = 1
for i in range(N):
  for j in range(S + 1):
    if j >= A[i]:
      DP[i + 1][j] = (DP[i][j] * 2 + DP[i][j - A[i]]) % MOD
    else:
      DP[i + 1][j] = (DP[i][j] * 2) % MOD

print(DP[-1][-1] % MOD)
### BUGGY CODE ###

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

ans = 0

x = 0

for i in range(n):
    for j in range(n-i):
        x += a[i+j]
        x %= m
        if x == 0:
            ans +=1
    x = 0

print(ans)

### FIXED CODE ###

from itertools import accumulate
from collections import Counter
import math


def combinations_count(n, r):
    return math.factorial(n)//(math.factorial(n-r) * math.factorial(r))

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

a = [0]+a
b = list(accumulate(a))

for i in range(len(b)):
    b[i]%=m


c = Counter(b)

ans = 0

for x in c:
    if c[x]>1:
        ans += combinations_count(c[x],2)

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

def combination(n, r):
    r = min(n - r, r)
    result = 1
    for i in range(n, n - r, -1):
        result *= i
    for i in range(1, r + 1):
        result //= i
    return result


N, M, K = map(int, input().split())
mod = 10 ** 9 + 7

NM = N * M
fa = [1] * (NM + 1)

for i in range(1, NM + 1):
    fa[i] = (fa[i - 1] * i) % mod

ans = 0
for i in range(1, N):
    ans += (i * M * M * (N - i)) % mod
    ans %= mod

for i in range(1, M):
    ans += (i * N * N *(M-i)) % mod
    ans %= mod

ans *= combination(NM-2, K-2)
ans %= mod
print(ans)


### FIXED CODE ###

class FactMod:

    def __init__(self, n, mod):
        self.mod = mod
        self.f = [1] * (n + 1)
        for i in range(1, n + 1):
            self.f[i] = self.f[i - 1] * i % mod

        self.inv = [pow(self.f[-1], mod - 2, mod)]
        for i in reversed(range(1, n + 1)):
            self.inv.append(self.inv[-1] * i % mod)
        self.inv.reverse()

    def fact(self, n):
        """
        :return: n!
        """
        return self.f[n]

    def comb(self, n, r):
        """
        :return: nCr
        """
        return self.f[n] * self.inv[n - r] * self.inv[r] % self.mod

N, M, K = map(int, input().split())
mod = 10 ** 9 + 7

NM = N * M
fa = [1] * (NM + 1)

for i in range(1, NM + 1):
    fa[i] = (fa[i - 1] * i) % mod

ans = 0
for i in range(1, N):
    ans += (i * M * M * (N - i)) % mod
    ans %= mod

for i in range(1, M):
    ans += (i * N * N *(M-i)) % mod
    ans %= mod

factmod = FactMod(NM-2, mod)
ans *= factmod.comb(NM-2, K-2)
ans %= mod
print(ans)
### BUGGY CODE ###

import collections
import math

n = int(input())

a = [str(sorted(input())) for _ in range(n)]
a.sort()
s = set(a)

l = []
for i in s:
    l.append(a.count(i))

ans = 0
for i in l:
    if i == 1:
        pass
    else:
        ans += (i-1) * i // 2

print(ans)

### FIXED CODE ###

import collections

n = int(input())

a = [str(sorted(input())) for _ in range(n)]
a.sort()
s = set(a)

c = collections.Counter(a)

ans = 0
for i in c.values():
        ans += (i-1) * i // 2

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

# -*- coding: utf-8 -*-
from collections import defaultdict,deque
N = int(input())
abc = [list(map(int, input().split())) for _ in range(N-1)]
Q, K = map(int, input().split())
xy = [list(map(int, input().split())) for _ in range(Q)]

graph = defaultdict(lambda: defaultdict(int))

for a,b,c in abc:
    graph[a-1][b-1] = c
    graph[b-1][a-1] = c

def xfs(v,g):
    que = deque()
    que.append([v,0])
    while len(que) > 0:
        i,dist = que.pop()  # 深さ優先探索        
        # i = que.popleft() #幅優先探索
        if i == g:
            return dist
        visited[i] = True
        for n, val in graph[i].items():
            if visited[n] == False:
                que.append([n,dist+val])

    return -1

for x,y in xy:
    visited = defaultdict(int)
    d1 = xfs(x-1, K-1)
    visited = defaultdict(int)
    d2 = xfs(K-1, y-1)
    print(d1 + d2)


### FIXED CODE ###

# -*- coding: utf-8 -*-
from collections import defaultdict,deque
N = int(input())
abc = [list(map(int, input().split())) for _ in range(N-1)]
Q, K = map(int, input().split())
xy = [list(map(int, input().split())) for _ in range(Q)]

# graph = defaultdict(lambda: defaultdict(int))
graph = [defaultdict(int) for _ in range(N)]

for a,b,c in abc:
    graph[a-1][b-1] = c
    graph[b-1][a-1] = c

def xfs(v):
    dist = [-1 for _ in range(N)]
    dist[v] = 0
    que = deque()
    que.append(v)
    while len(que) > 0:
        i = que.pop()  # 深さ優先探索        
        # i = que.popleft() #幅優先探索
        for n, val in graph[i].items():
            if dist[n] == -1:
                dist[n] = dist[i] + val
                que.append(n)
    return dist

dist = xfs(K-1)

for x,y in xy:
    print(dist[x-1] + dist[y-1])
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**7)
def dfs(now):
  res=1
  if vis[now]:
    if day[now]==-1:return -1
    else:return day[now]
  vis[now]=1
  for to in d[now]:
    r=dfs(to)
    if r==-1:return -1
    res=max(res,r+1)
  day[now]=res
  return res
n=int(input())
INF=10**18
c=[]
for i in range(n):
  for j in range(i+1,n):
    c+=[(i,j)]
d=dict(zip(c,[[] for _ in range(n*(n-1)//2)]))
s=[]
for i in range(n):
  a=list(map(int,input().split()))
  if i<a[0]-1:b=(i,a[0]-1)
  else:b=(a[0]-1,i)
  s+=[b]
  for j in a[1:]:
    j-=1
    if i<j:
      d[b]+=[(i,j)]
      b=(i,j)
    else:
      d[b]+=[(j,i)]
      b=(j,i)
vis=dict(zip(c,[0]*(n*(n-1)//2)))
day=dict(zip(c,[-1]*(n*(n-1)//2)))
ans=0
for i in s:
  di=dfs(i)
  if di==-1:
    print(-1)
    exit()
  ans=max(ans,di)
print(ans)

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**7)
def dfs(now):
  res=day[now]
  if vis[now]:
    if res==-1:return -1
    else:return res
  res=1
  vis[now]=1
  for to in d[now]:
    r=dfs(to)
    if r==-1:return -1
    res=max(res,r+1)
  day[now]=res
  return res
n=int(input())
v=0
si=[[0]*n for _ in range(n)]
for i in range(n):
  for j in range(i+1,n):
    si[i][j]=v
    v+=1
d=[[] for _ in range(v)]
s=[]
for i in range(n):
  a=list(map(int,input().split()))
  if i<a[0]-1:b=si[i][a[0]-1]
  else:b=si[a[0]-1][i]
  for j in a[1:]:
    j-=1
    if i<j:
      d[b]+=[si[i][j]]
      b=si[i][j]
    else:
      d[b]+=[si[j][i]]
      b=si[j][i]
vis=[0]*v
day=[-1]*v
ans=0
for i in range(v):
  di=dfs(i)
  if di==-1:
    print(-1)
    exit()
  ans=max(ans,di)
print(ans)
### BUGGY CODE ###

N = int(input())
A = input()
A = A.split()
A = [int(c) for c in A]
A.sort()
count = 0
for i in range(N):
    for j in range(N):
        if A[i] % A[j] == 0 and i != j:
            count += 1
            break
print(N-count)

### FIXED CODE ###

N = int(input())
A_list = list(map(int, input().split()))
A_list.sort()
A_max = A_list[-1]
count = 0
cnt_list = [1] * ((10 ** 6) + 1)
for i in range(len(A_list)-1):
    if cnt_list[A_list[i]] == 1:
        for j in range((A_max // A_list[i]) + 1):
            cnt_list[A_list[i] * j] = 0
        if A_list[i] != A_list[i+1]:
            count += 1
if cnt_list[A_list[-1]] == 1:
    count += 1
print(count)
### BUGGY CODE ###

N, K = map(int, input().split())
tmp = input().split(' ')
A = []

for i in range(N):
    A = A + [int(tmp[i])]
Z = [N]*N

while K > 0 and A != Z:
    K = K - 1
    B = [0]*(N+1)
    for i in range(N):
        l =  max(0,i-A[i])
        r =  min(N-1,i+A[i])
        B[l]+=1
        B[r+1]-=1

    A[0] = B[0]
    for i in range(1,N):
        A[i]=A[i-1]+B[i]

print(' '.join(map(str,A)))

### FIXED CODE ###

def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))

    Z = [N]*N

    while K > 0 and A != Z:
        K-=1
        B = [int(0)]*(N+1)
        for i in range(N):
            B[max(int(0),i-A[i])]+=1
            B[min(N-1,i+A[i])+1]-=1
        for i in range(1,N):
            B[i]+=B[i-1]

        A = B[0:N]

    print(' '.join(map(str,A)))

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

S = input()

MOD = 10**9+7

dp = [[0 for _ in range(13)] for _ in range(len(S) + 1)]


dp[0][0] = 1



for index in range(1, len(S) + 1):
    s = S[len(S) - index ]
    mul = (10 ** (index - 1)) % 13
    if s == '?':
        for pre_index in range(13):
            for i in range(10):
                next_i = (i * mul  +  pre_index ) % 13
                dp[index][next_i] += dp[index - 1][pre_index] % MOD
    else:
        i = int(s)
        for pre_index in range(13):
            next_i = (i * mul +  pre_index ) % 13
            dp[index][next_i] += dp[index - 1][pre_index] % MOD




print(dp[len(S)][5] % MOD)



### FIXED CODE ###

S = input()
 
MOD = 10**9+7
 
dp = [[0]*13 for _ in range(len(S) + 1)]
 
 
dp[0][0] = 1
 
for index in range(len(S)):
    if S[index] == '?':
        for pre_index in range(13):
            for i in range(10):
                next_i = (i +  pre_index * 10 ) % 13
                dp[index+1][next_i] += dp[index][pre_index] 
                dp[index+1][next_i] %= MOD

    else:
        for pre_index in range(13):
            i = int(S[index])
            next_i = (i +  pre_index  * 10) % 13
            dp[index+1][next_i] += dp[index][pre_index] 
            dp[index+1][next_i] %= MOD
 
 
 
print(dp[len(S)][5])
### BUGGY CODE ###

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

if M == 0:
  print(-1)
  exit()

INF = 10**6
pqc = [tuple(map(lambda x:int(x)-1,input().split())) for _ in range(M)]

to1d={v:{} for v in range(N)}
count=2
for p,q,c in pqc:
  if not to1d[p].get(c):
    to1d[p][c] = count
    count += 1
  if not to1d[q].get(c):
    to1d[q][c] = count
    count += 1

G = [{} for _ in range(count)]
for p,q,c in pqc:
  v1,v2 = to1d[p][c],to1d[q][c]
  G[v1][v2] = G[v2][v1] = 0
  
for v in range(N):
  if len(to1d[v])<=1: continue
  tmp = list(to1d[v].keys())
  for i in range(len(tmp)-1):
    for j in range(i+1,len(tmp)):
      v1,v2 = to1d[v][tmp[i]],to1d[v][tmp[j]]
      G[v1][v2] = G[v2][v1] = 1
        
def dijkstra(start = 0, goal = 1):
    from heapq import heappop, heappush
    NN = len(G)
    d = [INF]*NN
    d[start] = 0
    que = []
    heappush(que, start)
    while que:
        p = divmod(heappop(que),NN)
        v = p[1]
        if d[v] < p[0]: continue
        for u in G[v].keys():
            if d[u] > d[v] + G[v][u]:
                d[u] = d[v] + G[v][u]
                heappush(que, d[u]*NN+u)
        if v == goal: return d[goal]
    return d[goal]

for c in to1d[0].keys():
  v = to1d[0][c]
  G[0][v] = 1
for c in to1d[N-1].keys():
  v = to1d[N-1][c]
  G[v][1] = 0
  
ans = dijkstra(0,1)
print(ans if ans < INF else -1)

### FIXED CODE ###

def main():
  N,M=map(int,input().split())

  if M == 0:
    print(-1)
    exit()

  INF = 10**6
  pqc = [tuple(map(lambda x:int(x)-1,input().split())) for _ in range(M)]

  to1d={v:{} for v in range(N)}
  count=2
  for p,q,c in pqc:
    if not to1d[p].get(c):
      to1d[p][c] = count
      count += 1
    if not to1d[q].get(c):
      to1d[q][c] = count
      count += 1

  G = [{} for _ in range(N+count)]
  for p,q,c in pqc:
    v1,v2 = to1d[p][c],to1d[q][c]
    G[v1][v2] = G[v2][v1] = 0

  for i in range(N):
    if len(to1d[i])<=1: continue
    for c in to1d[i].keys():
      v = to1d[i][c]
      G[v][count] = 1
      G[count][v] = 0
    count += 1

  def dijkstra(start = 0, goal = 1):
      from heapq import heappop, heappush
      NN = len(G)
      d = [INF]*NN
      d[start] = 0
      que = []
      heappush(que, start)
      while que:
          p = divmod(heappop(que),NN)
          v = p[1]
          if d[v] < p[0]: continue
          for u in G[v].keys():
              if d[u] > d[v] + G[v][u]:
                  d[u] = d[v] + G[v][u]
                  heappush(que, d[u]*NN+u)
          if v == goal: return d[goal]
      return d[goal]

  for c in to1d[0].keys():
    v = to1d[0][c]
    G[0][v] = 1
  for c in to1d[N-1].keys():
    v = to1d[N-1][c]
    G[v][1] = 0

  ans = dijkstra(0,1)
  print(ans if ans < INF else -1)
  
if __name__=="__main__":
  main()
### BUGGY CODE ###

def solve():
    N = int(input())
    S = input()

    ans = 0
    for i in range(10):
        for j in range(10):
            for k in range(10):
                num = [i,j,k]
                idx = 0
                for digit in S:
                    digit = int(digit)
                    if digit == num[idx]:
                        idx += 1
                    if idx == 3:
                        ans += 1
                        break
    
    print(ans)

if __name__ == '__main__':
    solve()

### FIXED CODE ###

def solve():
    N = int(input())
    S = input()

    cnt = 0
    for i in range(1000):
        target = str(i).zfill(3)
        idx = 0
        for ch in S:
            if ch == target[idx]:
                idx += 1
                if idx == 3:
                    cnt += 1
                    break
    
    print(cnt)

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

def main():
    a = input().split(" ")
    K = int(a[0])
    S = int(a[1])
    X = Y = Z = count = 0
    for x in range(K + 1):
        for y in range(K + 1):
            for z in range(K + 1):
                xyz = x + y + z
                if xyz == S:
                    count += 1
    print(count)

if __name__ == '__main__':
    main()

### FIXED CODE ###

def main():
    a = input().split(" ")
    K = int(a[0])
    S = int(a[1])
    X = Y = Z = count = 0

    for x in range(K + 1):
        for y in range(K + 1):
            xy = x + y
            if S - xy <= K and 0 <= S - xy:
                count += 1
    print(count)

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

import numpy as np

K = int(input())

total = 0
for i in range(1, K + 1):
    for j in range(1, K + 1):
        for k in range(1, K + 1):
            total = total + np.gcd.reduce([i, j, k])

print(total)

### FIXED CODE ###

import math
import collections

K = int(input())

# intで初期化するため0が返る
cnt = collections.defaultdict(int)
for i in range(1, K + 1):
    for j in range(1, K + 1):
        key = math.gcd(i, j)
        # 最大公約数をkeyにし、同じ最大公約数の出現回数を保持
        cnt[key] = cnt[key] + 1

total = 0
for k in range(1, K + 1):
    for key in cnt.keys():
        # 出現済みの最大公約数との最大公約数を取り、出現回数分を加算する
        total = total + math.gcd(k, key) * cnt[key]

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

from collections import Counter

N = int(input())
*A, = map(int, input().split())
C = Counter(A)

if 1 in C:
    if C[1] == 1:
        print(1)
    else:
        print(0)
    exit()

ans = 0
for k, v in C.items():
    if v > 1:
        continue
    for i in range(2, int(k**0.5)+1):
        if k % i == 0:
            if i in C:
                break
            if k // i in C:
                break
    else:
        ans += 1
print(ans)


### FIXED CODE ###

from collections import Counter

def main():
    N = int(input())
    *A, = map(int, input().split())
    C = Counter(A)

    MAX = 1000005
    T = [0]*MAX

    ans = 0
    for a in C.keys():
        if T[a]:
            continue
        else:
            for i in range(2*a, MAX, a):
                T[i] = 1

    ans = 0
    for a, n in C.items():
        if n == 1 and T[a] == 0:
            ans += 1

    print(ans)


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

N = int(input())
S = []
for i in range(N):
  S.append(input())
C = []
for i in range(N):
  C.append(S.count(S[i]))
m = max(C)
S_new = sorted(set(S))
for s in S_new:
  if S.count(s) == m:
    print(s)

### FIXED CODE ###

import collections
N = int(input())
S = []
for i in range(N):
  S.append(str(input()))
A = collections.Counter(S)
m = max(A.values())
for s in sorted(set(S)):
  if A[s] == m:
    print(s)
### BUGGY CODE ###

MOD = 1000000007
n = int(input())
nums = list(map(int, input().split()))
result = 0
for i in range(n-1):
    for j in range(i+1, n):
        N = ((nums[i] % MOD)*(nums[j] % MOD)) % MOD
        result += N
        result = result % MOD
print(result)

### FIXED CODE ###

MOD = 1000000007
n = int(input())
nums = list(map(int, input().split()))
x = sum(nums)
y = sum([(nums[i]**2) for i in range(n)])
print(((x**2 - y)//2)% MOD)
### BUGGY CODE ###

from bisect import insort_left, bisect_left, bisect_right
n = int(input())
s = input()
q = int(input())
dic = {}
for ind, c in enumerate(s):
    if c in dic:
        dic[c].append(ind)
    else:
        dic[c] = [ind]

for _ in range(q):
    t, a, b = input().split()
    a = int(a)-1
    if t=='1':
        find_c = False
        for c, li in dic.items():
            if a in li:
                li.remove(a)
            if c==b:
                insort_left(li, a)
                find_c = True
        if not find_c:
            dic[b] = [a]
        dic = {c:li for c, li in dic.items() if len(li)>0}
    else:
        b = int(b)-1
        tmp = 0
        for li in dic.values():
            if bisect_left(li, a) < bisect_right(li, b):
                tmp += 1
        print(tmp)


### FIXED CODE ###

from bisect import insort_left, bisect_left
n = int(input())
s = list(input())
Q = int(input())
query = [input() for _ in range(Q)]
dic = {chr(i+ord('a')):[] for i in range(26)}
for ind, c in enumerate(s):
    dic[c].append(ind)

for q in query:
    t, a, b = q.split()
    a = int(a)-1
    if t=='1':
        if s[a]==b:
            continue
        ind = bisect_left(dic[s[a]], a)
        dic[s[a]].pop(ind)
        insort_left(dic[b], a)
        s[a] = b
    else:
        b = int(b)-1
        tmp = 0
        for li in dic.values():
            if li and a<=li[-1] and li[bisect_left(li, a)] <= b:
                tmp += 1
        print(tmp)
### BUGGY CODE ###

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

if n % 2 == 0:
    for i in range(n):
        if i % 2 == 0:
            b.append(a[i])
        else:
            b.insert(0, a[i])
else:
    for i in range(n):
        if i % 2 == 0:
            b.insert(0, a[i])
        else:
            b.append(a[i])


for i in range(n):
    print(b[i],'', end = '')
print()


### FIXED CODE ###

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

if n % 2 == 0:
    for i in range(n):
        if i < int(n / 2):
            print(a[n - 2 * i - 1],'', end = '')
        else:
            print(a[2 * i - n],'', end = '')
else:
    for i in range(n):
        if i <= n // 2:
            print(a[n - 2 * i - 1],'', end = '')
        else:
            print(a[2 * i - n],'', end = '')
print()
### BUGGY CODE ###

n, q = map(int, input().split())
s = input()
array = []
for i in range(n-1):
    if (s[i] == "A" and s[i+1] == "C"):
        array.append(i)

for i in range(q):
    a, b = map(int, input().split())
    ans = 0
    for m in array:
        if (a-1 <= m < b-1):
            ans += 1
    print(ans)

### FIXED CODE ###

n, q = map(int, input().split())
s = input()
ac = [0]*n
for i in range(n-1):ac[i+1] = ac[i] + (s[i:i+2]=="AC")
for i in range(q):
    l,r=map(int,input().split())
    print(ac[r-1]-ac[l-1])
### BUGGY CODE ###

N, K = map(int, input().split())

A_list = list(map(int, input().split()))
A_list = [A - 1 for A in A_list]

path = [0]
town = 0
k = K
j = 0
while k > 0:
  town = A_list[town]
                     
  if town in path:
    #print("town is {}".format(town))
    #print("path is {}".format(path))
    first_visit = path.index(town)
    loop_size = j - first_visit + 1
    #print("loop_size is {}".format(loop_size))
    #print("k is {}".format(k))
    k = (k-1) % loop_size 
    #print("k is now {}".format(k))
    path = []
    continue
    
  path.append(town)
    
  k = k - 1
  j = j + 1

print(town+1)

### FIXED CODE ###

N, K = map(int, input().split())

A_list = list(map(int, input().split()))
A_list = [A - 1 for A in A_list]

path = [0]
town = 0
k = K
j = 0

while k > 0:
  town = A_list[town]
   
  if k % 10000 == 0:
    if town in path:
      #print("town is {}".format(town))
      #print("path is {}".format(path))
      first_visit = path.index(town)
      loop_size = j - first_visit + 1
      #print("loop_size is {}".format(loop_size))
      #print("k is {}".format(k))
      k = (k-1) % loop_size 
      #print("k is now {}".format(k))
      town = path[first_visit + k]
      break
    
  path.append(town)
    
  k = k - 1
  j = j + 1

print(town+1)
### BUGGY CODE ###

from collections import deque
import sys
from collections import defaultdict
import copy
import numpy as np
# input = sys.stdin.readline



H, W = map(int, input().split())
C = [list(input()) for _ in range(H)]
gone = np.zeros((H,W))
cot = 0
que = deque()
next_que =  deque()

for h in range(H):
    for w in range(W):
        if C[h][w] == "#":
            gone[h][w] = 1
            next_que.append((h,w))
            cot += 1
INF = 10 ** 9
go = [[1, 0], [0, 1], [-1, 0], [0, -1]]
ans  = 0
que = next_que
while cot != H*W:
    que = copy.deepcopy(next_que)
    next_que = deque()
    while que:
        h,w = que.popleft()
        for temp in go:
            gx,gy = temp
            nx = w + gx
            ny = h + gy
            if 0<= nx < W and 0<= ny < H and gone[ny][nx] != 1: #行って無かったら，行く
                gone[ny][nx] = 1
                next_que.append( (ny,nx))
                cot += 1
    ans += 1
print(ans)





### FIXED CODE ###

from collections import deque
import sys
from collections import defaultdict
import copy
# input = sys.stdin.readline



H, W = map(int, input().split())
C = [list(input()) for _ in range(H)]
gone = [[0] * W for _ in range(H)]
cot = 0
que = deque()

que_count = 0
for h in range(H):
    for w in range(W):
        if C[h][w] == "#":
            gone[h][w] = 1
            que.append((h,w))
            que_count += 1
            cot += 1
INF = 10 ** 9
go = [[1, 0], [0, 1], [-1, 0], [0, -1]]
ans  = 0
nq = 0
while cot != H*W:
    while que_count != 0 and cot != H*W:
        h,w = que.popleft()
        que_count -= 1

        for temp in go:
            # この時，実際に行くのかは不明
            gx,gy = temp
            nx = w + gx
            ny = h + gy

            if 0<= nx < W and 0<= ny < H and gone[ny][nx] != 1: #行って無かったら，行く
                # この時に実際に移動する
                gone[ny][nx] = 1
                que.append( (ny,nx))
                nq += 1
                cot += 1
    que_count = nq
    nq = 0
    ans += 1
print(ans)