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):






"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from typing import Dict, List, Optional, Set, Tuple


def solve(values: List[int], nb: int) -> int:
    seen = {}
    cur = 0
    move = 0
    while move < nb and cur not in seen:
        seen[cur] = move
        move += 1
        cur = values[cur] - 1
    if move == nb:
        return cur + 1
    cycle_length = move - seen[cur]
    _nb_cycles, rest = divmod(nb - move, cycle_length)
    LOG.debug((cur, cycle_length, move, seen))
    for _ in range(rest):
        cur = values[cur] - 1
    return cur + 1


def do_job():
    "Do the work"
    LOG.debug("Start working")
    N, K = map(int, input().split())
    values = list(map(int, input().split()))
    assert len(values) == N
    result = solve(values, K)
    print(result)


def print_output(testcase: int, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case 
    
    


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None

if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    do_job()
    return 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())


class memoized:
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.
    """

    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        try:
            return self.cache[args]
        except KeyError:
            value = self.func(*args)
            self.cache[args] = value
            return value
        except TypeError:
            
            
            return self.func(*args)

    def __repr__(self):
        """Return the function's docstring."""
        return self.func.__doc__

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

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

def main():
    N, K = map(int, readline().rstrip().split())
    A = list(map(int, readline().rstrip().split()))
    d = {i+1: a for i, a in enumerate(A)}
    if K <= N:
        pre = 1
        for _ in range(K):
            pre = d[pre]
        print(pre)
        return

    pre = 1
    visited = set([1])
    visited_l = [1]
    for i in range(N):
        pre = d[pre]
        if pre in visited:
            break
        visited.add(pre)
        visited_l.append(pre)
    
    loop_start = visited_l.index(pre)
    loop = i - loop_start + 1

    num_loop = (K - loop_start) // loop
    now = loop_start + num_loop * loop
    for i in range(now+1, K+1):
        pre = d[pre]
    
    print(pre)

if __name__ == '__main__':
    main()

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

visi_point = collections.defaultdict(list)

posi = 1
for i in range(K):
    next_posi = A[posi]
    if len(visi_point[next_posi]) >= 2:
        break
    visi_point[next_posi].append(i+1)
    posi = next_posi


for k, v in visi_point.items():
    if K in v:
        print(k)
        break
    if len(v) >= 2:
        if (K - v[0]) % (v[1] - v[0]) == 0:
            print(k)
            break

Solution (Python):
def read_int():
    return int(input())

def read_int_map():
    return map(int,input().split(' '))

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

def read_s_list_loop(n):
    return [input() for _ in range(n)]

N,K = read_int_map()
An = read_int_list()
memo = [0]*(N+1)
memo_indx = [0]*(N+1)
memo[1] = 1
memo_indx[1] = 0
seq_an = [1]
next_place = An[0]
for i in range(len(An)):
    if memo[next_place] == 0:
        seq_an.append(next_place)
        memo[next_place] = 1
        memo_indx[next_place] = i + 1
        next_place = An[next_place-1]
    else:
        break
loop_idx = memo_indx[next_place]
loop_list = seq_an[loop_idx:]
if K <= len(seq_an)-1:
    print(seq_an[K])
else:
    num = (K - len(seq_an)) % len(loop_list)
    print(loop_list[num])

Solution (Python):


n, k = map(int, input().split())
x = list(map(int, input().split()))
count = 1
machi = 0
machi_list = [0]
next_machi = x[machi] - 1
machi_dict = {}
while True:
    if next_machi in machi_dict:
        break
    count += 1
    machi_dict[next_machi] = 1
    machi_list.append(next_machi)
    machi = next_machi
    next_machi = x[machi] - 1

z = 0
for i in range(0, count):
    if machi_list[i] == next_machi:
        z = i
        break
loop_machi_list = machi_list[z:]
if k < z:
    machi = machi_list[k] + 1
    print(machi)
else:
    k = k - z
    machi = loop_machi_list[k % len(loop_machi_list)] + 1
    print(machi)

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

p = 0

if K > N:
    city = [-1]*N
    city[0] = 1
    while city[A[p]-1] == -1:
        city[A[p]-1] = city[p]+1
        p = A[p]-1
    K = (K-city[p]) % (city[p]-city[A[p]-1]+1)
    p = A[p]-1

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

print(p+1)

Solution (Python):
n,k = map(int,input().split())
a = [0]+list(map(int,input().split()))
b = [0]*(n+1)
cnt = 0
temp = 1
rep = 0
while 1:
    cnt += 1
    if b[temp] == 0:
        b[temp] = cnt
    else:
        rep = cnt-b[temp]
        
        
        break
    temp = a[temp]

if (k-b[temp]+1) >= 0:
    for i in range((k-b[temp]+1) % rep):
        temp = a[temp]
    print(temp)
    exit()
else:
    temp = 1
    for i in range(k):
        temp = a[temp]
    print(temp)

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

B = [1] + [A[1]]
S = set(B)
i = 1
while i+1 == len(S):
    B.append(A[B[i]])
    S.add(A[B[i]])
    i += 1

for i in range(len(B)-1):
    if B[i] == B[-1]:
        a = i
        break

if K <= a:
    print(B[K])
else:
    print(B[a+ ((K-a) % (len(B)-a-1))])

Solution (Python):
n, k, *a = map(int, open(0).read().split())
now = 0
st = set()
ls = []
while not now in st:
    st.add(now)
    ls.append(now)
    now = a[now]-1
bi = ls.index(now)
lp = len(ls) - bi
if k<=bi: print(ls[k]+1)
else:
    k -= bi
    k %= lp
    print(ls[bi+k]+1)

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

rec=[-1]*(n+1)
rec[1]=0
now=1
wp=0
flag=False
while k>wp:
    rec[now]=wp
    nx=a[now]
    rest=k-wp
    loop=rec[now]-rec[nx]+1
    if rest<loop:
        flag=True

    if rec[nx]==-1 or flag:
        wp+=1
        now=nx
    else:
        rest%=loop
        wp=k-rest
        flag=True
print(now)

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
L = [1]
s = set()
s.add(1)
now = 1
for _ in range(N):
    if A[now - 1] in s:
        K -= L.index(A[now - 1])
        if K >= 0: K %= len(L) - L.index(A[now - 1])
        break
    L.append(A[now - 1])
    s.add(A[now - 1])
    now = A[now - 1]


print(L[K + L.index(A[now - 1])])

Solution (Python):
n, k = map(int, input().split())
g = list(map(lambda x: int(x)-1, input().split()))

visited = [False] * n
dist = [0] * n
v = 0
leng = 0

for i in range(n+10):
    if i == k: print(v+1); exit()
    if visited[v]:
        leng = i - dist[v]
        k -= dist[v]
        break
    visited[v] = True
    dist[v] = i
    v = g[v]

for i in range(k % leng):
    v = g[v]

print(v+1)

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

order = []
now = 1
count = 0
d = defaultdict(int)


for i in range(n):
    if d[now]!=0:
        s=d[now]-1
        g=i
        break
    order.append(now)
    d[now] = i+1
    now = a[now-1]


if k<=s:
    print(order[k])
else:
    k-=s
    loop = order[s:g]
    print(loop[k%len(loop)])

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)


def dfs(v, s):
    global origin, cycle
    path[v] = s
    nv = A[v]
    if path[nv] >= 0:
        origin = nv
        cycle = (s + 1) - path[nv]
    else:
        dfs(nv, s + 1)


N, K = map(int, input().split())
A = list(map(lambda x: int(x) - 1, input().split()))
origin = 0
cycle = 0
path = [-1] * N
dfs(0, 0)

if K <= path[origin]:
    for i, s in enumerate(path):
        if s == K:
            print(i + 1)
            break
else:
    rest = K - path[origin]
    rest %= cycle
    for i, s in enumerate(path):
        if s == path[origin] + rest:
            print(i + 1)
            break

Solution (Python):
import sys
from collections import deque

N, K = map(int, sys.stdin.readline().strip().split())
tmp = list(map(int, sys.stdin.readline().strip().split()))

A = [a-1 for a in tmp]

visited = set()
loop = []

q = deque()
q.append(0)
start = float("inf")
end = float("inf")

count = 0
while q and count <= N:
    s_town = q.popleft()
    
    if s_town in visited:
        start = loop.index(s_town)
        end = len(loop)
        break
    visited.add(s_town)
    loop.append(s_town)
    n_town = A[s_town]
    q.append(n_town)
    count += 1


if start >= K:
    print(loop[K]+1)
else:
    res = K - start
    res %= (end - start)
    
    print(loop[start + res]+1)

Solution (Python):
import sys

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

cnt = 0
current = 0
roads = []
reached = [-1 for _ in range(N)]

while True:
    if reached[current] >= 0:
        initial = reached[current]
        mod = cnt - initial
        if K <= initial:
            print(roads[K]+1)
        else:
            k = (K-initial) % mod
            print(roads[initial:][k]+1)
        sys.exit()
    roads.append(current)
    reached[current] = cnt
    cnt += 1
    current = A[current] - 1

Solution (Python):
import sys
n, k = list(map(int, input().split()))
nums = [-1] + list(map(int, input().split()))

visited = [0 for _ in range(n + 1)]
path = [1]
cur = 1
visited[1] = 1
for i in range(k):
	cur = nums[cur]
	path.append(cur)
	if visited[cur] == 1:
		for idx, val in enumerate(path):
			if val == cur:
				break
		
		
		print(path[idx + (k - idx) % ((len(path) - idx - 1))])
		sys.exit()
	else:
		visited[cur] = 1
print(cur)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = float('inf')


n, k = Is()
A = LI()
A = [-1] + A


B = [1]
visited = {1}
loopstart = -1
def dfs(num):
    global loopstart
    tmp = A[num]
    if tmp in visited:
        loopstart = tmp
    else:
        B.append(tmp)
        visited.add(tmp)
        dfs(tmp)

dfs(1)




C = []
for i in range(len(B)):
    if B[i] == loopstart:
        C = B[i:]

lb = len(B)
lc = len(C)
if k < lb:
    print(B[k])
else:
    print(C[(k-lb) % lc])

Solution (Python):
import collections
n, k = map(int, input().split())
dat = list(map(int, input().split()))
maze = []
initmaze=[]
recurmaze=[]
used = [-1] * (n + 10)
cur = 0
cnt = 0
while True:
    if used[cur] != -1:
        break
    used[cur] = cnt
    maze.append(cur)
    cur = dat[cur] - 1
    cnt += 1

recurpoint = used[cur]

initmaze = maze[:recurpoint]
recurmaze = maze[recurpoint:]





l = len(maze)
li = len(initmaze)
lr = len(recurmaze)
if k < li:
    print(initmaze[k] + 1)
else:
    k -= li
    print(recurmaze[k%lr] + 1)

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

def solve(k, A, N):
    p = 0
    k0 = k
    while k:
        if k&1 ==1:
            p = A[p]
        A = [A[A[x]] for x in range(N)]
        k = k >> 1
        
    
    return p + 1


print(solve(K, A, N))

Solution (Python):
import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, chain
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    num = 1
    for i in range(n, n-k, -1):
        num = num * i % modp
    den = 1
    for i in range(2, k+1):
        den = den * i % modp
    return num * get_inv(den, modp) % modp

def comb_from_list(n, k, modp, fs, invs):   
    return fs[n] * invs[n-k] * invs[k] % modp



class UnionFindEx:
    def __init__(self, size):
        
        self.roots = [-1] * size
    def getRootID(self, i):
        r = self.roots[i]
        if r < 0:   
            return i
        else:
            r = self.getRootID(r)
            self.roots[i] = r
            return r
    def getGroupSize(self, i):
        return -self.roots[self.getRootID(i)]
    def connect(self, i, j):
        r1, r2 = self.getRootID(i), self.getRootID(j)
        if r1 == r2:
            return False
        if self.getGroupSize(r1) < self.getGroupSize(r2):
            r1, r2 = r2, r1
        self.roots[r1] += self.roots[r2]    
        self.roots[r2] = r1
        return True

Yes = 'Yes'
No = 'No'


def main():
    N, K = mis()
    A = [a-1 for a in mis()]
    B = [None]*N
    now = 0
    B[now] = 0
    for i in range(1, K+1):
        now = A[now]
        K -= 1
        if B[now] is not None:
            K %= (i - B[now])
            break
        B[now] = i
    for _ in range(K):
        now = A[now]
    print(now+1)

main()

Solution (Python):
visited=[0]
visited_set=set()
visited_set.add(0)
n,k=map(int,input().split())
a=list(map(int,input().split()))
next1=0
next2=-1
while True:
    next2=a[next1]-1
    next1=next2
    if next2 in visited_set:
        break
    else:
        visited.append(next2)
        visited_set.add(next2)

if k<len(visited):
    print(visited[k]+1)
else:
    loop_len=(len(visited)-visited.index(next2))
    k-=(len(visited)-loop_len)
    print(visited[k%loop_len+visited.index(next2)]+1)

Solution (Python):
import sys


def input():
    return sys.stdin.readline().strip()


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

pos = A[1]
path = [1]
visited = {1}
cycle_start = -1
for _ in range(N):
    if pos in visited:
        cycle_start = pos
        break
    visited.add(pos)
    path.append(pos)
    pos = A[pos]

if cycle_start > 0:
    cycle_start_idx = path.index(cycle_start)
    acyclic_path = path[:cycle_start_idx]
    cyclic_path = path[cycle_start_idx:]
    if K < len(acyclic_path):
        print(acyclic_path[K])
    else:
        print(cyclic_path[(K - len(acyclic_path)) % len(cyclic_path)])
else:
    print(path[K])

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

check = [-1] * n
i = 0
count = 0
while True:
    if check[i] != -1:
        lsize = count - check[i] 
        tail = count - lsize
        break
    check[i] = count
    count += 1
    i = an[i] - 1

l = k
if k > tail:
    l = ((k - tail) % lsize) + tail

for i in range(n):
    if check[i] == l:
        print(i + 1)
        break

Solution (Python):
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

N, K = rl()
A = rl()

edges = {}
for i, a in enumerate(A):
	edges[i] = a-1

mem = {}
k = 0
n = 0
while True:
	if k == K:
		print(n+1)
		exit()
	if n in mem:
		break
	mem[n] = k
	k += 1
	n = edges[n]

p = k-mem[n]
idx = (K - k) % p

for i in range(idx):
	n = edges[n]
print(n+1)

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

if A[1] == 1:
    print(1)
    exit()


B = [1]


C = [False] * (n + 1)
C[1] = True


while True:
    B.append(A[B[-1]])
    if C[B[-1]]:
        break
    C[B[-1]] = True



s = B.index(B[-1])




if k < s:
    print(B[k])
    exit()


B = B[B.index(B[-1]):-1]
print(B[(k - s) % len(B)])

Solution (Python):
import sys

sys.setrecursionlimit(10**7)

def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    visited = [False] * N
    cnt = [0] * N
    visited[0] = True
    B = [0]
    def dfs(s):
        tmp = A[s] - 1
        

        if visited[tmp]:
            B[0] = cnt[tmp]
            for i in range(N):
                if i == tmp:
                    continue
                cnt[i] -= cnt[tmp]
            cnt[tmp] = 0
            return
        
        cnt[tmp] = cnt[s] + 1
        visited[tmp] = True
        if cnt[tmp] == K:
            print(tmp + 1)
            exit()
        dfs(tmp)
    dfs(0)
    K -= B[0]
    t = K % (max(cnt)+1)
    for i in range(N):
        if cnt[i] == t:
            print(i+1)
            exit()
        
if __name__ == "__main__":
    main()

Solution (Python):

N,K=map(int,input().split())
A=list(map(int,input().split()))
visited=[0 for i in range(N+1)]
p=1
path=[p]
visited[p]=1
p=A[p-1]
while visited[p]==0:
    path.append(p)
    visited[p]=1
    p=A[p-1]
i=path.index(p)
if(K<i):
    print(path[K])
else:
    K-=i
    print(path[i+K%(len(path)-i)])

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, k = LI()
A = LI()
now = 0
D = {0:-1}
for i in range(min(k, n)):
    now = A[now] - 1
    if now in D:
        break
    D[now] = i

if k < n:
    print(now + 1)
    exit()

k -= (i + 1)
b = now
c = k % (i - D[now])
for j in range(c):
    b = A[b] - 1

print(b + 1)

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

for i in range(N):
    now = tour[-1]
    if gone[now]:
        save = now
        break
    gone[now] = 1
    tour.append(A[now])

save_idx = tour.index(save)

if K <= save_idx:
    print(tour[K])
    exit()

loop = tour[save_idx+1:]
K = K - save_idx - 1
print(loop[K % len(loop)])

Solution (Python):
import numpy as np
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
    n,k=INTM()
    a=LIST()
    vst=[0]*n
    vst[0]=1
    loop=[]
    temp=1
    for i in range(k):
        temp=a[temp-1]
        if vst[temp-1]==0:
            vst[temp-1]=1
        elif vst[temp-1]==1:
            loop.append(temp)
            vst[temp-1]=2
        else:
            temp=loop[-1]
            cost=k-i
            break
        if i==k-1:
            cost=0
    if cost!=0:
        print(loop[(cost-1)%len(loop)])
    else:
        print(temp)
                    
                
if __name__ == '__main__':
    do()

Solution (Python):

''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 \
   /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/input.txt"
exit $?
'''
import sys

def _ia(): return map(int, sys.stdin.readline().strip().split())


def main():
    n, k = _ia()
    a = [ai-1 for ai in _ia()]
    d = [[0]*n for _ in range(60)]
    d[0] = a
    for i in range(59):
        now = d[i+1]
        prev = d[i]
        for j in range(n):
            now[j] = prev[prev[j]]

    now = 0
    for i in range(k.bit_length()):
        if k & 1:
            now = d[i][now]
        k >>= 1

    return now + 1

if __name__ == "__main__":
    print(main())

Solution (Python):

def solve(N, K, As):
    current = 1
    count = 0
    teleport = {i + 1 : v for i, v in enumerate(As)}
    dist = {}

    while current not in dist:
        dist[current] = count
        count += 1
        current = teleport[current]
        if K == count:
            return current

    loop_size = count - dist[current]
    K -= dist[current]
    K %= loop_size
    K += dist[current]

    current = 1
    while K > 0:
        current = teleport[current]
        K -= 1
    return current




















if __name__ == "__main__":
    N, K = tuple(map(int, input().split(" ")))
    As = list(map(int, input().split(" ")))
    print(solve(N, K, As))

Solution (Python):
N, K = map(int, input().split())
A = [0] + list(map(int, input().split()))
visited = [-1 for _ in range(N+1)]
path = [1]
visited[1] = 0
pos = 1
endi = -1
for i in range(1, N+1):
    pos = A[pos]
    if i == K:
        endi = -i
        break
    if visited[pos] > -1:
        endi = i
        break
    visited[pos] = i

if endi < 0:
    print(pos)
else:
    loop = endi - visited[pos]
    ansi = (K-visited[pos])%loop
    for i in range(ansi):
        pos = A[pos]
    print(pos)

Solution (Python):
n,k=map(int,input().split())
ar=list(map(int,input().split()))
vis=[0 for i in range(n+1)]
x=1
seq=[1]
go=0
rep=0
ct=1
while (vis[x]==0):
    vis[x]=ct
    seq.append(ar[x-1])
    x=ar[x-1]
    ct+=1
    if vis[x]!=0:
        rep=ct-vis[x]
        go=vis[x]
if k<=go:
    print(seq[k])
else:
    print(seq[go+(k-go)%rep])

Solution (Python):
import sys

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

town = [0] * n
town[0] = 1
track = [1]
now = 1
cnt = 0
while True:
    now = a[now-1]
    town[now-1] += 1
    cnt += 1
    if town[now-1] > 1:
        loop = now
        break
    track.append(now)
    if cnt == k:
        print(now)
        sys.exit()

idx = track.index(loop)
ans = (k - idx) % (cnt - idx)
print(track[idx:][ans])

Solution (Python):
N, K = (int(i) for i in input().split())
A = [int(i) for i in input().split()]
V = [-1]*N
W = [-1]*N
x = 0
V[0] = 0
W[0] = 0
for i in range(1, K+1):
    x = A[x] - 1
    W[i] = x
    if V[x] == -1:
        V[x] = i
    else:
        x = W[V[x] + (K-i) % (i -V[x])]
        break
print(x+1)