Problem:
 Score: 400 points    Problem Statement  The Kingdom of Takahashi has N towns, numbered 1 through N .  There is one teleporter in each town. The teleporter in Town i  (1 \leq i \leq N) sends you to Town A_i .  Takahashi, the king, loves the positive integer K . The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.  Help the king by writing a program that answers this question.      Constraints   2 \leq N \leq 2 \times 10^5  1 \leq A_i \leq N  1 \leq K \leq 10^{18}         Input  Input is given from Standard Input in the following format:  N  K  A_1  A_2  \dots  A_N       Output  Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.        Sample Input 1 4 5
3 2 4 1      Sample Output 1 4  If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4 .       Sample Input 2 6 727202214173249351
6 5 2 5 3 2      Sample Output 2 2

Solution (Python):
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right


from functools import reduce
from pprint import pprint

INF = float("inf")

def myinput():
    return map(int,input().split())

def mylistinput(n):
    return [ list(myinput()) for _ in range(n) ]

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

n,k = myinput()
a = list(myinput())

ls = [-1]*n

ls[0] = 0
s = 0
for i in range(n):
    if (i+1)==k:
        s = a[s] - 1
        print(s+1)
        exit()
    else:
        s = a[s] - 1
        if ls[s]<0:
            ls[s] = i + 1
            
        else:
            b = ls[s]
            w = (i+1) - b
            c = (k-b)%w
            g = ls.index(c+b) + 1
            
            print(g)
            exit()

Solution (Python):
n,k = map(int,input().split())
a = list(map(int,input().split()))

machi = 1
toutatu = []
pypyosoi = set()
while not machi in pypyosoi:
	toutatu.append(machi)
	pypyosoi.add(machi)
	machi = a[machi-1]

saigo = machi
num = toutatu.index(saigo)
unchi = toutatu[num:]
cnt = len(unchi)

if num > k:
	print(toutatu[k])
else:
	print(unchi[(k-num)%cnt])

Solution (Python):
n,k = map(int, input().split())
a = list(map(int, input().split()))

root = [1]

for i in range(n):
    t = a[root[i]-1]
    if (t == 0):
        break
    a[root[i]-1] = 0
    root.append(t)
x =  root.index(root[-1])
bef = root[0:x]

loop = root[x:-1]



if (k < len(bef)):
    print(bef[k])
else:
    p = ((k - len(bef)) % len(loop))
    
    print(loop[p])

Solution (Python):
import sys
input = sys.stdin.readline

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

cnt, town = 0, 1
l, s = [], set()
while True:
    town = a[town - 1]
    cnt += 1
    if cnt == k:
        print(town)
        exit()
    if town in s:
        loop_start = town
        break
    l.append(town)
    s.add(town)


loop_cnt = l.index(loop_start)
loop = l[loop_cnt:]
loop_len = len(loop)
k -= loop_cnt
print(l[loop_cnt:][k%loop_len-1])

Solution (Python):
ma = lambda :map(int,input().split())
ni = lambda:int(input())
import collections
import itertools
import math
n,k = ma()
A  = list(map(lambda x:int(x)-1,input().split()))
vis = [False]*n
cnt = [0]*n
vis[0] = 1
st = 0
c = 0
cyc = 0
l = 0
while True:
    c+=1
    nex = A[st]
    if c==k:
        print(nex+1)
        exit()
    if vis[nex]:
        cyc = cnt[st] - cnt[nex] +1
        l = cnt[st]+1
        break
    cnt[nex] = c
    vis[nex]=True
    st = nex
k = (k-l)%cyc
st = nex
while k>0:
    nex = A[st]
    st = nex
    k-=1
print(nex+1)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
graph = [set() for i in range(N)]
for i, a in enumerate(A):
    graph[i].add(a - 1)

queue = [0]
seen = {0}
path = []
while queue:
    new = []
    for cur in queue:
        path.append(cur)
        for nei in graph[cur]:
            if nei not in seen:
                new.append(nei)
                seen.add(nei)
    queue = new

if 0 in graph[path[-1]]:
    rest = K % len(path)
    print(path[rest] + 1)
else:
    if K < len(path):
        print(path[K] + 1)
    else:
        start = graph[path[-1]].pop()
        index = path.index(start)
        rest = (K - len(path[:index])) % len(path[index:])
        print(path[index:][rest] + 1)

Solution (Python):
import sys
l = sys.stdin.readline().strip()
N, K = map(int, l.split())
l = sys.stdin.readline().strip()
A = [0] + list(map(int, l.split())) 
visited = [-1] * (len(A)+1)

remain = K
crt = 1
entrance = -1
while remain > 0:
    remain -= 1
    
    if visited[crt] == -1:
        visited[crt] = K - remain
        crt = A[crt]
    else:
        entrance = crt
        crt = A[crt]
        break


if entrance == -1:
    print(crt)
else:
    loop = (K-remain) - visited[entrance] 
 
    later = remain % loop
    for i in range(later):
        crt = A[crt]
    print(crt)

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
n, k = map(int, input().split())
a = list(map(int, input().split()))

length = [-1] * n
path = [-1, []]
route = []


def func(now, depth):
    global path, length, a, route
    route.append(now)
    if length[now] == -1:
        length[now] = depth
        func(a[now]-1, depth+1)
    else:
        path = [length[now], route[length[now]:depth]]


func(0, 0)

if (k < path[0]):
    print(route[k] + 1)
else:
    tmp = k - path[0]
    tmp %= len(path[1])
    print(path[1][tmp] + 1)

Solution (Python):
import sys
from _collections import deque
N,K = map(int,input().split())
A = list(map(int,input().split()))
for i in range(len(A)):
    A[i] = A[i]-1
used = [0]*N
m = 0
c = 0
used[m] = 1

while(True):
    m = A[m]
    c += 1
    if c == K:
        print(m+1)
        sys.exit()
    if used[m] == 1:
        break
    else:
        used[m] = 1

loop = m
h = K-c
ans = deque([loop])
c = 0
p = loop
while(True):
    p = A[p]
    c += 1
    if p == loop:
        break
    ans.append(p)

print(ans[h%c]+1)

Solution (Python):
from collections import Counter

n, k = map(int, input().split())
a = list(map(int, input().split()))
check = [0] * n



target = 0
for i in range(k):
    if (check[target] == 2):  
        
        count = Counter(check)
        num_2 = count[2]
        
        temp = k - (i)
        mod = temp % num_2
        for j in range(mod):
            aaa = a[target]
            target = aaa - 1

        ans = target + 1
        break

    else:
        check[target] += 1
        aaa = a[target]
        target = aaa - 1

        ans = target + 1

print(ans)

Solution (Python):
N, K = map(int, input().split())
teleps = list(map(int, input().split()))
teleps.insert(0, 0)
current = 1
routes = []
memory = set([])
roop_count = 0
for _ in range(K):
    
    if current not in memory:
        memory.add(current)
    else:
        
        index = routes.index(current)
        roop_count = len(routes) - index
        di = (K - index) % roop_count
        current = routes[index+di]
        break
    routes.append(current)
    current = teleps[current]
print(current)

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
s = 1
B = [0]*(10**6)
B[0] = 1
C = [0]*(10**6)
C[1] = 1 
for i in range(K):
    s -= 1
    s = A[s]
    B[i + 1] = s
    C[s] += 1
    if C[s] > 1:
        k = B.index(s)
        l = i + 1 - k
        s = 10**10
        break
if s < 10**10:
    print(s)
else:
    B1 = B[k:k+l]
    r = (K - k)%l
    print(B1[r])

Solution (Python):
def main():
    _, K = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]
    history = [1]
    
    history_dict = {1:0}
    last_city = -1
    for x in range(K):
        now = A[history[-1]-1]
        
        if now in history_dict:
            last_city = now
            break
        history.append(now)
        history_dict[now] = x+1

    if last_city == -1:
        print(history[-1])
    
    else:
        index = history_dict[last_city]
        mod = (K - index) % (len(history) - index)
        
        print(history[index + mod]) 

if __name__ == "__main__":
    main()

Solution (Python):
N,K = map(int,input().split())
A = [0]+list(map(int,input().split()))

num = [0]*(N+1)
inv = []

p = 1
count = 1
while num[p] == 0:
    num[p] = count
    inv.append(p)
    p = A[p]
    count += 1

m = max(num)








if K >= num[p]:
    print(inv[(K-(num[p]-1))%(m-(num[p]-1))+num[p]-1])
else:
    print(inv[K])

Solution (Python):
N,K= list(map(int, input().split()))
A= list(map(int, input().split()))

path = [0]*N
a = 0

for j in range(N+1):
    count = j
    a = A[a]-1
    if path[a]!= 0:
        b = path[a]
        c = j+1-path[a]
        break
    else:
        path[a] = j+1

mod = (K-b)%c

if count > K:
    print(path.index(K)+1)
else:
    print(path.index(mod+b)+1)

Solution (Python):
N, K = map(int, input().split())
A = [int(i) - 1 for i in input().split()]

def solve() :
  global K
  visited = [-1] * N
  visited[0] = 0

  cur = 0
  while True :
    nex = A[cur]
    if visited[cur] == K - 1 :
      return nex + 1
      
    if visited[nex] == -1 :
      visited[nex] = visited[cur] + 1
      cur = nex
    else :
      
      i = visited[nex]
      
      j = visited[cur] + 1
      K -= i
      K %= (j - i)
      cur = nex
      break
      
  while K > 0 :
    cur = A[cur]
    K -= 1
    
  return cur + 1
    
print(solve())

Solution (Python):
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
from collections import defaultdict
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
import numpy as np
INF = float("inf")











N,K = map(int,input().split())
A = list(map(int,input().split()))
if K <= 3 * N:
    cur = 1
    for i in range(K):
        cur = A[cur-1]
    print(cur)
else:
    d = defaultdict(int)
    cur = 1
    for i in range(3*N):
        cur = A[cur-1]
        d[cur] += 1
    if d[1] != 0:
        cur = 1
        for i in range(1,N+1):
            cur = A[cur-1]
            if cur == 1:
                f = i
        num = K % f
        if num == 0:
            print(1)
        else:
            cur = 1
            for i in range(num):
                cur = A[cur-1]
            print(cur)
    else:
        cnt = 0
        for i in range(1,N+1):
            if d[i] == 1:
                cnt += 1
        cur = 1
        for i in range(cnt+1):
            cur = A[cur-1]
        start = cur
        for i in range(1,N+1):
            cur = A[cur-1]
            if cur == start:
                f = i
                break
        K = K - cnt -1
        num = K % f
        if num == 0:
            print(start)
        else:
            cur = start
            for i in range(num):
                cur = A[cur-1]
            print(cur)

Solution (Python):
import sys;input=lambda:sys.stdin.readline().rstrip();aint=lambda:int(input());ints=lambda:list(map(int,input().split()))
import math;floor,ceil=lambda x:int(math.floor(x)),lambda x:int(math.ceil(x))
from functools import reduce;gcd=lambda*x:reduce(math.gcd,x);lcm=lambda*x:reduce(lambda x,y:(x*y)//gcd(x,y),x,1)
from collections import deque
import bisect
Yes=lambda b:print("Yes"if b else"No");YES=lambda b:print("YES"if b else"NO")
is_even=lambda x:True if x%2==0 else False

def main():
    n,k=ints()
    a=ints()
    passed=[]
    flg=0
    p=0
    while flg==0:
        if a[p] == 'passed':
            flg=1
            s=passed.index(p)
            break
        else:
            passed.append(p)
            pp=p
            p=a[pp]-1
            a[pp]='passed'
    l=len(passed)
    if k<l:
        print(passed[k]+1)
    else:
        print(passed[(k-s)%(l-s)+s]+1)

if __name__ == '__main__':
    main()

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))

vst = [False for i in range(N)]
plc = [0]

for i in range(N):
    mm = plc[-1]
    mm2 = A[mm]-1
    if vst[mm2]:
        break
    vst[mm] = True
    plc.append(A[mm]-1)

li = []
flg = False
for i in range(len(plc)):
    if plc[i]==mm2:
        flg = True

    if not(flg):
        continue

    li.append(plc[i])





ans = (K-len(plc))%len(li)
if (K-len(plc)) >=0:
    print(li[ans]+1)
else:
    print(plc[K]+1)

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))

F=[-1]*N
l=0
prev=0
while True:
  if F[prev]!=-1:
    break
  
  if l==K:
    print(prev+1);exit()
  F[prev]=l
  l+=1
  prev=A[prev]-1
  
l = (K-F[prev])%(l-F[prev])

for i in range(l):
  prev=A[prev]-1
print(prev+1)

Solution (Python):
a = input().split(" ")
N = eval(a[0])
K = eval(a[1])
dic = {}
b = input().split(" ")
n_lst = [-1]
for i in range(1, N + 1):
    dic[i] = eval(b[i - 1])
    n_lst.append(-1)
ans = 1
lst = []
length = 0
while K > 0:
    if n_lst[ans] != -1:
        left = n_lst[ans]
        zq = length - left
        K = K % zq
        if K == 0:
            break
    else:
        n_lst[ans] = length
        length += 1
    ans = dic[ans]
    K -= 1

print(ans)

Solution (Python):
import numpy as np
n, k = map(int, input().strip().split())
as_ = np.array(list(map(int, input().strip().split())))
as_ -= 1


first_visited = [-1] * n

now = 0
num_teleport = 0
while True:
    if first_visited[now] == -1:
        first_visited[now] = num_teleport
    else:
        
        loop_length = num_teleport - first_visited[now]
        loop_start_point = now
        time_to_start_point = first_visited[now]
        break

    now = as_[now]
    num_teleport += 1


now2 = 0
if k > time_to_start_point:
    k -= time_to_start_point
    k %= loop_length
    now2 = loop_start_point

for i in range(k):
    now2 = as_[now2]

print(now2 + 1)

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
n, k = map(int, input().split())

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

check = [False for _ in range(n + 1)]
route = [1]
check[1] = True
now = a[0]
cnt = 1
while (1):
    
    
    if cnt == k:
        print(now)
        exit()

    if check[now]:
        break
    else:
        check[now] = True
        route.append(now)
        cnt += 1
        now = a[now - 1]

indexnow = route.index(now)
roop_length = len(route) - indexnow
new_route = route[indexnow:]





print(new_route[(k - indexnow) % roop_length])

Solution (Python):















mod = int(1e9+7)
INF = 1<<29
lINF = 1<<35

def readInt():
    return list(map(int,input().split()))

def main():
    n,k = readInt()
    a = readInt()
    pos = 0
    visit = [0] * n
    move = []
    roop = []
    while visit[pos]!=2:
        if visit[pos]==0:
            move.append(pos)
        else:
            roop.append(pos)
        visit[pos] += 1
        pos = a[pos] - 1
    num = 0
    if len(move)>k:
        print(move[k]+1)
    else:
        num = (k - (len(move)-len(roop))) % len(roop)
        print(roop[num]+1)
    return

if __name__=='__main__':
    main()

Solution (Python):
def main():
    N, K = map(int, input().split())
    A_i = list(map(lambda x: int(x)-1, input().split()))

    v = [False] * N
    c = 0

    while True:
        if K == 0:
            print(c+1)
            return
        if v[c]:
            break
        v[c] = True
        c = A_i[c]
        K -= 1

    x = c
    y = 0
    while True:
        if K == 0:
            print(c+1)
            return
        c = A_i[c]
        K -= 1
        y += 1
        if x == c:
            break

    K = K % y
    while True:
        if K == 0:
            print(c+1)
            return
        c = A_i[c]
        K -= 1


main()

Solution (Python):
n, k = map(int, input().split())
A = list(map(int, input().split()))
route = [1]
dest = A[0]
check = {i: False for i in range(n)}
while not check[dest - 1]:
    check[dest - 1] = True
    route.append(dest)
    dest = A[dest - 1]
ind = route.index(dest)
cycle = route[ind:]
if k >= ind:
    ans = (k - ind) % len(cycle)
    print(cycle[ans])
else:
    print(route[k])

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))

move = [-1] * N
point = 0
count = 0
L = [0]
while True:
    if move[point] != -1:
        break
    move[point] = A[point] - 1
    point = move[point]
    L.append(point)
    count += 1
loop_start = L.index(move[point])
loop_L = L[loop_start:]

if K <= count:
    print(L[K] + 1)
    exit()
print(loop_L[(K - count - 1) % len(loop_L)] + 1)

Solution (Python):





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

    f_loop = [1]
    passed = set(f_loop)

    next_idx = 1
    while True:
        next_town = As[next_idx-1]
        if next_town in passed:
            idx_head = f_loop.index(next_town)
            n_loop = len(f_loop) - idx_head
            break

        passed.add(next_town)
        f_loop.append(next_town)
        next_idx = next_town

    if idx_head + n_loop <= K:
        target = idx_head + (K - idx_head - n_loop) % n_loop
    else:
        target = K

    print(f_loop[target])


if __name__ == "__main__":
    main()

Solution (Python):
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
def resolve():
    N, K = lr()
    A = lr()
    vis = [-1]*(N+1)
    dis = [0]*(N+1)
    v = 1
    cnt = 0
    while vis[v] == -1:
        dis[cnt] = v
        vis[v] = cnt
        v = A[v-1]
        cnt += 1
    if K <= vis[v]:
        print(dis[K])
    else:
        print(dis[(K-vis[v])%(cnt-vis[v])+vis[v]])
resolve()

Solution (Python):
N, K = map(int, input().split())
As = list(map(lambda x: int(x)-1, input().split()))

cnt = 1
v = 0
checked = [-1]*N
checked[0] = 0
while True:
    v = As[v]
    if checked[v]!=-1:
        loop = cnt-checked[v]
        road = checked[v]
        break
    cnt += 1
    checked[v] = cnt-1

ite = K if K<=road else road+((K-road)%loop)

v = 0
for i in range(ite):
    v = As[v]

print(v+1)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N, K = map(int, rl().split())
    A = list(map(int, rl().split()))
    
    pos = dict()
    for idx, ai in enumerate(A):
        pos[ai] = idx + 1
    
    roop = 0
    u_set = set()
    u_set.add(1)
    counter = dict()
    counter[1] = 0
    ca = A[0]
    cnt = 1
    roop_s = 0
    b = 0
    while 1:
        if ca in u_set:
            if ca == roop_s:
                roop = cnt - counter[ca]
                break
            elif roop_s == 0:
                counter[ca] = cnt
                roop_s = ca
                b = cnt
        u_set.add(ca)
        ca = A[ca - 1]
        cnt += 1
    
    ans = 0
    if K < b:
        ca = A[0]
        cnt = 1
        while 1:
            if cnt == K:
                ans = ca
                break
            ca = A[ca - 1]
            cnt += 1
    else:
        m = (K - b) % roop
        ca = A[pos[roop_s] - 1]
        cnt = 0
        while 1:
            if cnt == m:
                ans = ca
                break
            ca = A[ca - 1]
            cnt += 1
    print(ans)


if __name__ == '__main__':
    solve()

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
from collections import defaultdict
d = defaultdict(int)
n=0
d[0]=1
i=2
while d[A[n]-1]==0:
  d[A[n]-1]+=i
  if i-1==K:
    print(A[n])
    exit(0)
  i+=1
  n=A[n]-1
K-=d[A[n]-1]-1
X=d[n]-d[A[n]-1]+1
n=A[n]-1
for i in range(K%X):
  n=A[n]-1
print(n+1)

Solution (Python):


def input_one_number():
    return int(input())

def input_multiple_number():
    return map(int, input().split())

def input_multiple_number_as_list():
    return list(map(int, input().split()))


N,K = input_multiple_number()
A = input_multiple_number_as_list()

isVisit = [-1]*N

orgK = K
now = 1
cnt = 0
looper = 0
while K > 0:
	if isVisit[now-1] >= 0:
		looper = cnt - isVisit[now-1]
		break

	isVisit[now-1] = cnt
	now = A[now-1]
	cnt += 1

K -= cnt
if K <= 0:
	now = 1
	K = orgK
else:
	K %= looper

for i in range(K):
	now = A[now-1]

print(now)

Solution (Python):
n,d=map(int,input().split())
x=[0]+list(map(int,input().split()))
N=n+1
y=list(range(N))


while d:
  if d&1:
    y=[x[y[i]] for i in range(N)]
  x=[x[x[i]] for i in range(N)]
  d>>=1
res=[0]*N

print(y[1])

Solution (Python):

import math

def input_num():
	ls = input().strip().split(" ")
	return [int(e) for e in ls]

n,k = input_num()
a_ls = input_num()

d = {}
now = 1
result_ls = [now]
cnt = 0
while True:
	d[now] = cnt
	now = a_ls[now-1]
	if now in d:
		bun = d[now]
		break
	result_ls.append(now)
	cnt += 1


if k < bun:
	print(result_ls[k])
else:
	jun = len(result_ls) - bun
	idx = bun + (k-bun)%jun
	print(result_ls[idx])

Solution (Python):


import sys

class DTeleporter:
    def solve(self, tc=0):
        n, k = [int(_) for _ in input().split()]
        a = [int(_) - 1 for _ in input().split()]
        done = dict()
        cur = 0
        steps = 0
        while cur not in done and steps < k:
            done[cur] = steps
            cur = a[cur]
            steps += 1
        
        if steps == k:
            print(cur + 1)
            return

        d = steps - done[cur]
        steps = steps + ((k - steps) // d) * d

        while steps < k:
            cur = a[cur]
            steps += 1

        print(cur + 1)


solver = DTeleporter()
input = sys.stdin.readline

solver.solve()

Solution (Python):


import sys
import pprint

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)


def main():
	log = Logger(0)
	n, k = map(int, sys.stdin.readline().split())
	a = list(map(int, sys.stdin.readline().split()))
	here = 1
	patarrn = []
	dist = [0]*n
	while 1:
		here = a[here-1]
		if dist[here-1]:
			break
		dist[here-1] = 1
		patarrn.append(here-1)
	log.print(here, patarrn)
	b = patarrn.index(here-1)
	if k <= len(patarrn):
		print(patarrn[k-1]+1)
		exit()
	patarrn = patarrn[b:]
	log.print(patarrn, b, patarrn[(k-b) % len(patarrn) - 1])
	print(patarrn[(k-b) % len(patarrn) - 1]+1)


main()

Solution (Python):
import itertools
import numpy as np

def main():
  n, k = [int(i) for i in input().split()]
  A = [None] + [int(i) for i in input().split()]

  slow = fast = 1

  for i in range(k):
    slow = A[slow]
    fast = A[A[fast]]
    if slow == fast:
      break
    if i == k-1:
      return slow

  slow = 1
  count = 0
  while slow != fast:
    slow = A[slow]
    fast = A[fast]
    count += 1

  branch = fast
  branch_num = count
  count = 1
  node = A[branch]
  while node != branch:
    node = A[node]
    count += 1
  
  idx = (k - branch_num) % count + branch_num
  ret = 1
  for _ in range(idx):
    ret = A[ret]
  return ret

print(main())

Solution (Python):
[N,K] = list(map(int,input().split()))
A = list(map(int,input().split()))

t = 0
now = 1
memo = [0]*(N+1)
memo[1]=1
jun = [1]
flag = 0
while t < K:
    t += 1
    next = A[now-1]
    if memo[next]>0:
        flag = 1
        break
    memo[next]=t+1
    jun.append(next)
    now = next
if flag ==0:
    print(now)
else:
    S = (t+1)-memo[next]
    for i in range(len(jun)):
        if jun[i]==next:
            start = i
            break
    K += -1*start
    amari = K%S
    print(jun[start+amari])

Solution (Python):
import sys

n, k = map(int, input().split())
a = list(map(int, input().split()))
a = [0] + a

visited = set([])
hist = [-1 for _ in range(n+1)]
cur = 1
cnt = 0
d = 0

while True:
    if cnt == k:
        print(cur)
        sys.exit()
    if hist[cur] != -1:
        d = cnt - hist[cur]
        break
    hist[cur] = cnt
    cur = a[cur]
    cnt += 1

k -= hist[cur]
index = hist[cur] + k % d


for i, histi in enumerate(hist):
    if index == histi:
        print(i)
        sys.exit()

Solution (Python):

"""
Created on Sun May 10 20:54:33 2020

@author: Kanaru Sato
"""

n,k = list(map(int,input().split()))
_ = list(map(int,input().split()))
np = [0]+_

cp = 1
dic = {"1":0}
kaisu = 0

while True:
    kaisu += 1
    cp = np[cp]
    if cp in dic:
        break
    else:
        dic[cp] = kaisu

loopstart = cp
looplength = kaisu-dic[loopstart]

if k <= dic[loopstart]:
    ans = [i for i, v in dic.items() if v == k]
    print(ans[0])
else:
    k = k-dic[loopstart]
    k = k%looplength
    ans = [i for i, v in dic.items() if v == dic[loopstart]+k]
    print(ans[0])

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    cnt = 0
    used = [-1] * N
    used[0] = 0
    cur = 0
    loop_cnt = 0
    start = 0
    for i in range(1, N+1):
        cur = A[cur] - 1
        if i == K:
            print(cur+1)
            sys.exit() 
        if used[cur] == -1:
            used[cur] = i
            continue
        else:
            loop_cnt = i
            start = cur
            break
    K -= loop_cnt
    loop_cnt -= used[start]
    x = K % loop_cnt
    for i in range(N):
        if used[i]-used[start] == x:
            print(i+1)

if __name__ == '__main__':
    main()

Solution (Python):

import bisect
import collections
import sys

sys.setrecursionlimit(1000000)
input = sys.stdin.readline
ACMOD = 1000000007
INF = 1 << 62


def lmi():
    return list(map(int, input().split()))


def llmi(n):
    return [lmi() for _ in range(n)]


def main():
    N, K = lmi()
    A = lmi()
    c = [-1] * N
    current = 0
    d = dict()
    d[0] = 0
    c[0] = 0
    count = 0
    loop_start = -1
    for count in range(1,2 * N+2):
        _next = A[current] - 1
        c[_next] = count
        d[count] = _next
        current = _next
    for i in reversed(range(N)):
        if d[i] == d[N]:
            loop_size = N- i
            break
    if K <= 2*N:
        print(d[K] + 1)
    else:
        print(d[(K - N) % loop_size + N] + 1)
    
    
    


if __name__ == '__main__':
    main()

Solution (Python):
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,k = mi()
alis = li()
for i in range(n):
    alis[i] -= 1

dp = [0]*(n+1)
dp2 = [0]*(n+1)

ima = 0
for i in range(n):
    ima = alis[ima]
    if dp[ima] == 0:
        dp[ima] = i+1
    else:
        ragu = i+1
        dp2[ima] = i+1
        break
for i in range(1,n+1):
    ima = alis[ima]
    if dp2[ima] == 0:
        dp2[ima] = i + ragu
    else:
        ragu2 = ragu + i
        break

if k < ragu:
    for i in range(0,n):
        if dp[i] == k:
            print(i+1)
            exit()

else:
    delta = ragu2 - ragu
    for i in range(n):
        if dp2[i] == 0:
            continue
        else:
            tmp = k - dp2[i]
            if tmp % delta == 0:
                print(i+1)
                exit()

Solution (Python):
import collections

N,K = map(int,(input().split()))
a = list(map(int,(input().split())))
a.insert(0,-1)

now = 1
visit = [1]
again = collections.defaultdict(lambda:-1)
again[1] = 0
c = 0

for step in range(1,N+1):
    visit.append(a[now])
    if again[ a[now] ] == -1:
        again[ a[now] ] = step
    else:
        c += 1
        if c == 1:
            loop = a[now]
            loop_step = step
    now = a[now]

re = loop_step - again[loop]

if K <= again[loop]:
    print(visit[K])
else:
    tmp = again[loop]
    for key in again.keys():
        again[key] -= tmp
    amari = (K-tmp)%re
    for key in again.keys():
        if again[key] == amari:
            print(key)

"""
print(visit)
print(again[loop])
print(loop)
print(again)
print(loop_step)
print(re)
"""

Solution (Python):
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi

MOD = 10 ** 9 + 7
INF = 10 ** 18

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

if K <= 2 * 10 ** 5 + 2:
    ans = 1
    for i in range(K):
        ans = A[ans - 1]
    print(ans)
    exit()


cnt = [0] * (N + 1)
p = A[0]
c = 1

while 1:
    if cnt[p] == 0:
        cnt[p] = c
    else:
        c1 = cnt[p]
        c2 = c
        break
    p = A[p - 1]
    c += 1



B = [0, A[0]]
for _ in range(3 * 10 ** 5):
    B.append(A[B[-1] - 1])

BN = len(B)

for i in range(BN - 1, -1, -1):
    if i % (c2 - c1) == K % (c2 - c1):
        print(B[i])
        exit()

Solution (Python):
N,K = map(int,input().split())
A = list(map(int, input().split()))

l = [1]
kanryou_town = [0]*(N+1)
kanryou_town[1] = 1
now_town = 1
loop_town = 0
for i in range(N):
    now_town = A[now_town-1]
    if kanryou_town[now_town] == 1:
        loop_town = l.index(now_town)
        break
    else:
        kanryou_town[now_town] = 1
        l.append(now_town)

loop_num = len(l)-loop_town
if K > loop_town:
    num = (K - loop_town)%loop_num + loop_town
else:
    num = K




print(l[num])

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N):
    A[i] -= 1
L = [0]
t = 0
F = [-1 for _ in range(N)]
F[0] = 0
c = 1
while F[A[t]] == -1:
    t = A[t]
    F[t] = c
    c += 1
    L.append(t)
loop = c - F[A[t]]
buffer = c - loop
if K < buffer:
    print(L[K] + 1)
else:
    NL = L[buffer:]
    amari = (K - buffer) % loop
    print(NL[amari] + 1)

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
r=[0]
z=[True]*N
x=[-1]*N
x[0]=0
z[0]=False
n=A[0]-1
i=0
while z[n] and i<K:
    i+=1
    r.append(n)
    x[n]=i
    z[n]=False
    p=n
    n=A[n]-1
if i==K:
    print(p+1)
else:
    s=x[n]
    r=r[s:]
    l=len(r)
    t=(K-s)%l
    print(r[t]+1)

Solution (Python):




def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    visited = [0]
    visited_set = set()
    now = 0
    for k in range(K):
        now = A[now] - 1
        if now in visited_set:
            start = visited.index(now)
            shuki = k + 1 - start
            print(visited[start:][(K - start) % shuki] + 1)
            return
        visited.append(now)
        visited_set.add(now)
    print(visited[-1] + 1)



if __name__ == '__main__':
    main()

Solution (Python):
n,k = [int(x) for x in input().split()]
a = [int(x)-1 for x in input().split()]
loop = []
seen = [0]*n
num = 0
flag = 0
while k>0:
    if seen[num]==1:
        flag = 1
        break
    seen[num]=1
    loop.append(num)
    num = a[num]
    k-=1
if flag:
    index = loop.index(num)
    loop = loop[index:]
    print(loop[(k%len(loop))]+1)
else:
    print(num+1)