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



import sys
sys.setrecursionlimit(10**7)
from pprint import pprint as pp
from pprint import pformat as pf



import math

import bisect


class Solver:

    def __init__(self, n, k, a):
        self.n = n
        self.k = k
        self.a = a
        self.pos = 0 
        self.ticket = k
        self.diary = [False] * n
        self.nostalgia = False
        self.hometown = -1
        self.cycle_size = 0

    def run(self):
        
        self.pos = 0
        self.diary[0] = True
        while not self.nostalgia:
            
            
            if self.ticket == 0:
                return self.answer()
            self.jump()
        self.count_cycle_size()
        self.ticket = self.ticket % self.cycle_size
        while not self.ticket == 0:
            self.pos = self.a[self.pos]
            self.ticket -= 1
        return self.answer()

    def count_cycle_size(self):
        self.cycle_size = 1
        self.pos = self.a[self.pos]
        while not (self.pos == self.hometown):
            self.pos = self.a[self.pos]
            self.cycle_size += 1

    def jump(self):
        self.ticket -= 1
        self.pos = self.a[self.pos]
        if self.diary[self.pos]:
            self.nostalgia = True
            self.hometown = self.pos
        self.diary[self.pos] = True

    def answer(self):
        
        return self.pos + 1


def make_to_city_id_starts_from_0(a):
    for i, v in enumerate(a):
        a[i] = v - 1

if __name__ == '__main__':
    n, k = list(map(int, input().split()))
    a = list(map(int, input().split()))
    make_to_city_id_starts_from_0(a)

    
    ans = Solver(n, k, a).run()
    
    print(ans)

Solution (Python):

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


l=[1]
s=set(l)
for i in range(k):
    x=a[l[i]-1]
    if x in s:
        break
    else:
        l.append(x)
        s.add(x)

b=l.index(x)
c=len(l)-b
print(l[((k-b)%c)+b])

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

mv = 0
i = 1
B = [1]
visit = [0]*N
visit[0] = 1
while True:
    i = A[i-1]
    mv += 1
    B.append(i)
    if mv == K:
        break
    elif visit[i-1] == 1:
        st = B.index(i)
        sa = mv - st
        break
    visit[i-1] = 1
        
if mv == K:
    print(i)
else:
    print(B[st + (K-st)%sa])

Solution (Python):
import bisect
import collections
import heapq
import math
import operator as op
from collections import Counter
from functools import reduce

import numpy as np


def get_inputs(cast_func=None):
    if cast_func is None:
        return input().split()
    else:
        return list(map(cast_func, input().split()))


def get_input(cast_func=None):
    if cast_func is None:
        return input()
    else:
        return cast_func(input())


def main():

    N, K = get_inputs(int)
    As = get_inputs(int)
    As = [None, ] + As

    prev = 1
    history = {}
    history[1] = 0
    for n_teles in range(1, K+1):
        cur = As[prev]
        if cur in history:
            
            len_cyc = n_teles - history[cur]
            
            
            for _ in range((K - n_teles) % len_cyc):
                cur = As[cur]
            print(cur)
            return
        else:
            prev = cur
            history[cur] = n_teles
    print(cur)




































if __name__ == '__main__':
    main()

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

i=0
s=1
way=[1]
co={1:[0]}
while  1==1:
    i+=1
    way.append(a[s-1])
    if a[s-1] not in co:
        co[a[s-1]]=[i]
    else:
        if k<co[a[s-1]][0]:
            print(way[k])
            break
        else:
            print(way[co[a[s-1]][0]+(k-co[a[s-1]][0])%(i-co[a[s-1]][0])])
            break
    s=a[s-1]

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n,k=map(int,input().split())
    A=list(map(int,input().split()))
    if A[0]==1:
        print(1)
        sys.exit()
    cur_a=1
    cunt=0
    visited=[False]*n
    visited[0]=True
    route=[1]
    for _ in range(k):
        next_a=A[cur_a-1]
        if visited[next_a-1]:
            loop=len(route)-route.index(next_a)
            cunt-=loop-1
            break
        cur_a=next_a
        cunt+=1
        route.append(cur_a)
        visited[cur_a-1]=True
    else:
        print(next_a)
        sys.exit()
    
    
    k-=cunt
    k=k%loop
    
    print(route[cunt+k])
    

if __name__=='__main__':
    main()

Solution (Python):
import sys

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

alr = {}
now = 1
i = 0
while not now in alr.keys():
    alr[now] = i
    now = A[now-1]
    i += 1
    if i == K:
        print(now)
        sys.exit()

place = alr[now]
circle = len(alr) - place
rem = (K - place) % circle
for k, v in alr.items():
    if v == place + rem:
        print(k)
        break

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:]
print(loop[(k - loop_cnt) % len(loop) - 1])

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
A=[-1]+A
still=[0]*(N+1)
still[1]=1
before=1
rS=-1
root=[1]
while True:
  dest=A[before]
  if still[dest]==1:
    rS=dest
    break
  else:
    still[dest]=1
    root.append(dest)
    before=dest

num=0
for i in root:
  if i==rS:
    break
  num+=1

if K<=num:
  print(root[K])
else:
  K-=num
  root2=root[num:]
  print(root2[K%len(root2)])

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

check = [0] * (n+10)
res = []
next = 0

for i in range(k):
    if check[next] == 0:
        check[next] = 1
        next = li[next]-1
    elif check[next] == 1:
        check[next] += 1
        res.append(next+1)
        next = li[next]-1
    else:
        cnt = len(res)
        k -= check.count(1)
        amari = k%cnt
        print(res[amari])
        break
else:
    print(next+1)

Solution (Python):
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]





N, K = mi()
A = li()
flag = [0]*N
l = []
i = 1
ind = 0
while True:
    flag[ind] = i
    l.append(ind+1)
    if not flag[A[ind]-1]:
        ind = A[ind]-1
    else:
        ind = A[ind]-1
        break
    i += 1

if K <= flag[ind] - 1:
    print(l[K])
    exit()

if ind != 0:
    K -= flag[ind] -1
    i -= flag[ind] -1
    l = l[flag[ind] -1:]
print(l[K%i])

Solution (Python):
n,k= map(int, input().split())
a= list(map(int, input().split()))
a=[0]+a
x=[0]*(n+1)
s=a[1]
x[1]=1
v1=[1]
cnt1=1
v2=[]
cnt2=0
for i in range(10**7):
    if x[s]==0:
        x[s]+=1
        cnt1+=1
        v1.append(s)
        s=a[s]

    elif x[s]==1:
        cnt2+=1
        x[s] += 1
        v2.append(s)
        s = a[s]
    else:
        break

if k<cnt1:
    print(v1[k])
else:
    q=(k-cnt1)%cnt2
    print(v2[q])

Solution (Python):
def task(n, k, a):
    cache = [0] * (n + 1)
    pos = 1
    sequence = [1]
    cache[1] = pos
    index = 1
    prefix = 0
    ks = k

    while True:
        index += 1
        nxt = a[pos - 1]

        if cache[nxt] != 0:
            prefix = cache[nxt] - 1
            cycle = sequence[prefix:]
            break

        sequence.append(nxt)
        cache[nxt] = index
        pos = nxt

        ks -= 1

        if ks == 0:
            print(nxt)
            return

    target = (k - prefix) % len(cycle)
    print(cycle[target])


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

Solution (Python):
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) 
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    


MOD = 10**9 + 7
INF = 2**31  

from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  

N, K = read_ints()

A = read_ints()
B = []
for a in A:
    B.append(a - 1)








nums_to_arrive = [-1] * N
nums_to_arrive[0] = 0
now = 0
while True:
    to = B[now]
    if nums_to_arrive[to] == -1:
        nums_to_arrive[to] = nums_to_arrive[now] + 1
        if nums_to_arrive[to] == K:
            print(to + 1)
            exit()
    else:
        break
    now = to
n1 = nums_to_arrive[to]
n2 = nums_to_arrive[now] + 1 - n1
base = to  



K = (K - n1) % n2  

now = base  
while K:
    to = B[now]
    K -= 1
    now = to
print(now + 1)

Solution (Python):
n,k = map(int,input().split())
a = list(map(lambda x: int(x)-1,input().split()))
towns = [0]
added = [-1] * n
added[0] = 0
for i in range(1,k+1):
    tmp = a[towns[-1]]
    pl = added[tmp]
    if pl != -1:
        loop = towns[pl:]
        last = (k-pl) % len(loop)
        print(loop[last]+1)
        exit()
    else:
        added[tmp] = i
        towns.append(tmp)
print(towns[-1]+1)

Solution (Python):

from sys import stdin
from operator import itemgetter
from collections import deque, Counter
import math
import pprint
from functools import reduce


MOD = 1000000007

def keta(kazu):
    kazu_str = str(kazu)
    kazu_list = [int(kazu_str[i]) for i in range(0, len(kazu_str))]
    return kazu_list

def gcd(*numbers):
    return reduce(math.gcd, numbers)

def combination(m,n):
    if n > m:
        return 'すまん'
    return math.factorial(m) // (math.factorial(m-n) * math.factorial(n))

def main():
    n, k = [int(x) for x in stdin.readline().rstrip().split()]
    a_1 = list(map(int,[int(x) for x in stdin.readline().rstrip().split()]))
    a_2 = [0] + [0] * (n-1)
    a_3 = []
    now = 1
    while True:
        now = a_1[now-1]
        a_3.append(now)
        if a_2[now-1]:
            break
        else:
            a_2[now-1] = 1
    start = a_3.index(a_3[-1])
    a_4 = a_3[:start]
    a_5 = a_3[start:-1]
    if k <= len(a_4):
        print(a_4[k-1])
    else:
        amari = k - len(a_4)
        
        print(a_5[(amari%len(a_5))-1])

main()

Solution (Python):
n, k = map(int, input().split())
tlist = list(map(int, input().split()))
check = [1]*n
town = 1
loop =[]
while bool(check[town-1]):
  check[town-1] = 0
  loop.append(town-1)
  town = tlist[town-1]
init = loop.index(town-1)
if k < init:
  print(loop[k]+1)
else:
  print(loop[init+(k-init)%(len(loop)-init)]+1)

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
d={}
cnt=[]
m=0
ans=0
for i in range(2*n):
  if a[m] in d:
    ans+=1
    cnt.append(a[m])
    if ans==k:
      print(a[m])
    break
  else:
    d[a[m]]=0
    cnt.append(a[m])
    ans+=1
    if ans==k:
      print(a[m])
      break
    m=a[m]-1
if ans!=k:
  if cnt[-1]==cnt[-2]:
    print(cnt[-1])
  else:
    cnt=cnt[cnt.index(cnt[-1]):-1]
    print(cnt[(k-ans)%len(cnt)])

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



visitted = [-1] * n
cur_town = 0
town_cnt = 0
visitted[0]=town_cnt
town_cnt+=1
while True:
    next_town = a[cur_town]
    if visitted[next_town]==-1:
        visitted[next_town]=town_cnt
        town_cnt+=1
        cur_town=next_town
    else:
        break

last_move = (k-town_cnt)%(town_cnt-visitted[next_town])
if k < town_cnt:
    print(visitted.index(k)+1)
else:
    cur_town=next_town
    for _ in range(last_move):
        next_town = a[cur_town]
        cur_town=next_town
    print(cur_town+1)

Solution (Python):
import sys
from math import log2,floor,ceil,sqrt



Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
 
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7

n,k = Ri()
a = Ri()
a= [0]+a
ans = []

dic = {}
prev = 1

ite  = 0
flag = -1
for i in range(n):
    if a[prev] not in dic:
        ans.append(a[prev])
        dic[a[prev]] = ite
        prev = a[prev]
        ite+=1
    else:
        flag = a[prev]
        break
start = dic[flag]

if k-1 < start:
    print(ans[k-1])
else:
    
    cyclen = len(ans)-start
    k-=1
    k -= start
    k%=cyclen
    print(ans[start+k])

Solution (Python):
N, K = map(int, input().split())
a = list(map(int, input().split()))
l = [1]
for i in range(N):
  l.append(a[l[i]-1])
p = l.index(l[N])
if K<=N:
  print(l[K])
else:
  x = (K-N+1)%(N-p)
  if x ==0:
    print(l[N-1])
  else:
    print(l[x+p-1])

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

step = 0
init_loop = 0
interval = 0
state = 1
visited = [-1]*(n+1)
visited[1] = 0
for i in range(1,3*n):
    state = a[state]
    if i == k:
        print(state)
        exit()
    if visited[state] >= 0:
        init_loop = visited[state]
        interval = i - init_loop
        break
    visited[state] = i

mod = (k - init_loop) % interval
for idx,v in enumerate(visited):
    if v == mod +init_loop:
        print(idx)
        exit()

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()


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

    pos = A[1]
    visited = {1}
    while pos not in visited:
        visited.add(pos)
        pos = A[pos]
    
    start = pos
    loop = 1
    pos = A[pos]
    while pos != start:
        pos = A[pos]
        loop += 1
    
    dist = 0
    pos = 1
    while pos != start:
        pos = A[pos]
        dist += 1

    
    
    if dist < K:
        K -= dist
        K %= loop
        pos = start
        for _ in range(K): pos = A[pos]
        print(pos)
    else:
        pos = 1
        for _ in range(K): pos = A[pos]
        print(pos)


if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, k = map(int, input().split())
    a = [int(i) - 1 for i in input().split()]
    s = 0
    m, l = 0, 0
    p = []
    h = set()
    for _ in range(n):
        p.append(s)
        h.add(s)
        s = a[s]
        if s in h:
            m = p.index(s)
            l = len(h) - m
            break
    if k <= m:
        print(p[k] + 1)
    else:
        print(p[(k - m) % l + m] + 1)

if __name__ == '__main__':
    main()

Solution (Python):
"""
N towns
teleporter each town
teleporter at town i -> town A_i
k-times teleporter after starting at town 1
"""

from collections import deque

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

visited = [0] * n
path = deque()
cur = 0

while not visited[cur]:
    visited[cur] = 1
    path.append(cur)
    cur = a[cur]

while path[0] != cur and k > 0:
    k -= 1
    path.popleft()


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

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


move = [a[i] - 1 for i in range(n)]

d = [-1 for _ in range(n)]
d[0] = 0
cur = 0
for _ in range(300000):
    to = move[cur]
    if d[to] == -1:
        d[to] = d[cur] + 1
    else:
        rou = d[cur] + 1 - d[to]
        rou_start = to
        break
    cur = to


if k < d[rou_start]:
    x = k
    rou_start = 0
else:
    x = (k - d[rou_start]) % rou
cur = rou_start
for _ in range(x):
    cur = move[cur]


print(cur + 1)

Solution (Python):
inf = 10**15
mod = 10**9+7

n,k = map(int, input().split())
a = list(map(int, input().split()))
firstkouho = []
roopkouho = []
visited = [False for i in range(n)]
tmp = 0
while visited[tmp] == False:
    visited[tmp] = True
    tmp2 = a[tmp] - 1
    tmp = tmp2
roopstart = tmp


tmp = 0
countstart = 0
while tmp != roopstart:
    firstkouho.append(tmp)
    tmp2 = a[tmp]-1
    tmp = tmp2
    countstart += 1

length = 1
roopkouho.append(roopstart)
if a[roopstart]-1 != roopstart:
    tmp = a[roopstart]-1
    while tmp != roopstart:
        roopkouho.append(tmp)
        length += 1
        tmp2 = a[tmp] - 1
        tmp = tmp2



if k < countstart:
    if countstart != 0:
        print(firstkouho[k]+1)
    else:
        print(1)
else:
    r = k-countstart
    print(roopkouho[r%length]+1)

Solution (Python):
n, k = map(int, input().split())
teleporter = list(map(int, input().split()))
loop = [0]
checked = [False] * n
checked[0] = True
next_teleporter = teleporter[0] - 1

while not checked[next_teleporter]:
    checked[next_teleporter] = True
    loop.append(next_teleporter)
    next_teleporter = teleporter[next_teleporter] - 1

if next_teleporter == loop[0] - 1:
    index = k % len(loop)
    print(loop[index] + 1)
else:
    for i in range(len(loop)):
        if next_teleporter == loop[i]:
            s = i
            break
    if s > k:
        print(loop[k] + 1)
    else:
        loop = loop[s:]
        index = (k - s) % len(loop)
        print(loop[index] + 1)

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

visited = [-1 for _ in range(N + 1)]
visited[1] = 0
cur = 1
precur = 0

cnt = 0
while cnt < K:
    precur = cur
    cur = A[cur]
    cnt += 1
    if visited[cur] > -1:
        break
    else:
        visited[cur] = cnt

if cnt == K:
    print(cur)
    exit()

ite = cnt - visited[cur]
x = (K - cnt + 1) % ite
cur = precur

cnt = 0
while cnt < x:
    cur = A[cur]
    cnt += 1
print(cur)
exit()

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

c = [None] * 200000
cc = set()
p = 0
st = 0
ed = 0
i = 0
while True:
    c[i] = p
    cc.add(p)
    i += 1
    p = a[p]
    if p in cc:
        st = c.index(p)
        ed = i
        break
if k < ed:
    print(c[k] + 1)
else:
    k -= st
    k %= ed - st
    print(c[st + k] + 1)

Solution (Python):
list=input().split(" ")
N=int(list[0])
K=int(list[1])
move_list=input().split(" ")
for i in range(N):
    move_list[i]=int(move_list[i])
move_list.insert(0,0)
list_count=[0 for i in range(N+1)]
find_loop=[]

now=1
count=0
flag=0
while(count<K):
    if list_count[now]==1:
        find_loop.append(now)
    elif list_count[now]==2:
        flag=1 
        break
    list_count[now]+=1
    now=move_list[now]
    count+=1

if flag==0:
    now=1
    for i in range(K):
        now=move_list[now]
    print(now)
    
else:
    tmp=(K-count)%len(find_loop)
    print(find_loop[tmp])

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

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

memo = [0]*(n+1)

for i in range(n):
    memo[i+1] = t[i]

move = 1

count = 0

check = [0]*(n+1)

while check[move] == 0 and count < k-1:
    check[move] += 1
    move=memo[move]
    count += 1

if k == count:
    print(memo[move])
else:
    count2 = 0
    check = [0]*(n+1)
    move_log = []
    while check[move] == 0:
        move_log.append(move)
        check[move] += 1
        move=memo[move]
        count2 += 1
    print(move_log[(k-count)%count2])

Solution (Python):
import sys

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


flag = [-1 for _ in range(n)]



stack = [a[0]-1]
flag[0] = 0
count = 0
while stack:
	u = stack.pop()
	if flag[u] == -1:
		stack.append(a[u] - 1)
		count += 1
		if count == k:
			print(u+1)
			sys.exit()
		flag[u] = count
	else:
		loop = count - flag[u] + 1
		
		num = (k - flag[u]) % loop
		
		break

if num == 0:
	print(u + 1)
else:
	ans = a[u]
	for i in range(num-1):
		ans = a[ans-1]
	print(ans)

Solution (Python):
n, k =[int(i) for i in input().split()]
a = [int(i) - 1 for i in input().split()]

go = dict()
res = []

go[0] = True
res = [0]

now = a[0]
while True:
    if now in go:
        break
    res.append(now)
    go[now] = True
    now = a[now]




amari = res.index(now)
xunhuan = res[amari:]


if k <= amari:
    print(res[k] + 1)
else:
    print(xunhuan[ (k - amari) % len(xunhuan)] + 1)

Solution (Python):
N, K = map(int, input().split())
dists = list(map(int, input().split()))
 
import sys
n = N - 1
idists = [d - 1 for d in dists]
visits = [-1] * N
 

now = 0
count = 0
while True:

    if visits[now] >= 0:
        break
    visits[now] = count
    now = idists[now]
    count += 1
    if count == K:
        print(now + 1)
        sys.exit()
 

cycle = count - visits[now]
rest = (K - count) % cycle
for _ in range(rest):

    now = idists[now]
print(now + 1)

Solution (Python):
import sys;input=lambda:sys.stdin.readline().rstrip();ints=lambda:list(map(int,input().split()))

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

if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int,input().split())
li = list(map(int,input().split()))
ans = [1]
nex = 1
f = [1]+[0]*(n-1)

for i in range(n):
    now = nex 
    nex = li[now-1] 
    
    if f[nex-1] == 1: 
        a = ans.index(nex) 
        b = ans.index(now)-a+1 
        break
    f[now-1] = 1
    ans.append(li[now-1])



if k <= a:
    print(ans[k])
else:
    x = (k-a)%b
    print(ans[a+x])

Solution (Python):
n, k = [int(i) for i in input().split()]
tel = [int(i) for i in input().split()]
been = [0 for _ in range(n)]
been[0] = 1

next = tel[0]
loop = [1]
for i in range(n):
	loop.append(next)
	if been[next-1] == 1:
		break
	been[next-1] = 1
	next = tel[next-1]

loop_begin = loop.index(tel[next-1])
loop_num = i - loop_begin + 2
if loop_begin >= k:
	ans = loop[k]
else:
	loop_remain = (k-loop_begin) % loop_num
	ans = loop[loop_begin+loop_remain]

print(ans)

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

k = 1
st = 0
c[0] = 1
cc = 1
for i in range(N):
    k = A[k-1]
    if c[k-1] == 1:
        st = T.index(k)
        f = T[:st]
        r = T[st:]
        break

    T.append(k)
    c[k-1] += 1
    cc += 1

ff = len(f)
if K < ff:
    print(f[K])
else:
    print(r[(K-ff)%(cc-ff)])

Solution (Python):
from collections import defaultdict

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

d = defaultdict(list)

p = 1
root = []



for i in range(K):
    d[p].append(i)
    root.append(p)
    if len(d[p]) == 2:
        s = d[p][0]
        e = i
        n = (K - s) % (e - s)
        p = root[s + n]
        break
    p = A[p - 1]





print(p)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)  
to_index = lambda x: int(x) - 1  
print_list_in_2D = lambda x: print(*x, sep="\n")  


def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

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

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())


def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

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


def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

N, K = MII_split()
As = LII_split()


visited = [False for _ in range(N)]
start = 1
visited[0] = True
loop = [start]
cur = start
for _ in range(N):
    nex = As[cur - 1]
    
    if not visited[nex - 1]:
        loop.append(nex)
        visited[nex - 1] = True
        cur = nex
    else:
        start_idx = loop.index(nex)
        before_num = start_idx
        befores = loop[:start_idx + 1]
        loop = loop[start_idx:]

        break






if K < before_num:
    print(befores[K])
else:
    K -= before_num
    idx = K % len(loop)
    print(loop[idx])

Solution (Python):
N, K = map(int, input().split())
G = [0]*N
src = list(map(int, input().split()))
for i,a in enumerate(src):
    G[i] = a-1
D = [-1]*N
D[0] = 0
cur = 0
dis = 0
while True:
    dis = dis+1
    cur = G[cur]
    if dis == K:
        print(cur+1)
        exit()
    if D[cur] == -1:
        D[cur] = dis
    else:
        cycle = dis - D[cur]
        K -= D[cur]
        target = K%cycle
        
        dis = 0
        if dis == target:
            print(cur+1)
            exit()
        while True:
            dis = dis+1
            cur = G[cur]
            if dis == target:
                print(cur+1)
                exit()

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

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



INF = 10**12
cnt = [-1 for _ in range(n)]
cur = 0
size = INF
idx = 0

for i in range(k):
    if cnt[cur] != -1:
        size = i - cnt[cur]
        idx = i
        for j in range((k - idx) % size):
            next_idx = a[cur] - 1
            cur = next_idx
        print(cur + 1)
        exit()
    cnt[cur] = i
    next_idx = a[cur] - 1
    cur = next_idx
print(cur + 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 sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
"""
閉路をmodを取って出力
閉路になっていない(回帰するなら)ならそこを出力
"""
n,k = map(int,readline().split())
lst1 = list(map(int,readline().split()))


visited = [-1]*n 
visited[0] = 0
now = 0
count = 1
mod = -1
lim = -1
while True:
    now = lst1[now] -1
    if visited[now] != -1: 
        mod = count - visited[now]
        lim = visited[now]
        break
    visited[now] = count

    count += 1
    
if k <= lim:
    for i in range(n):
        if visited[i] == k:
            print(i+1)
            exit()
else:
    res = (k-lim)%mod
    for i in range(n):
        if visited[i]-lim == res:
            print(i+1)
            exit()

Solution (Python):
from collections import deque

def main():
    def int_0(num):
        return int(num) - 1

    N, K = map(int, input().split())
    A = tuple(map(int_0, input().split()))
    
    
    INF = 10 ** 18
    visited = [False] * N
    dist = [INF] * N
    info  = {}
    def dfs(s):
        stack = deque()
        stack.append(s)
        visited[s] = True
        dist[s] = 0
        while stack:
            now = stack.pop()
            visited[now] = True
            nv = A[now]
            if visited[nv] == True:
                info["start"] = nv
                info["length"] = dist[now] - dist[nv] + 1
                info["f"] = dist[nv]
                break
            else:
                dist[nv] = dist[now] + 1
                stack.append(nv)
    dfs(0)

    if K <= N:
        now = 0
        for _ in range(K):
            now = A[now]
        print(now+1)
        exit()

    K -= info["f"]
    K %= info["length"]

    now = info["start"]
    for _ in range(K):
        now = A[now]
    print(now+1)


if __name__ == "__main__":
    main()

Solution (Python):
def solve(a, k):
    cycle = []
    visited = set()
    curr = 0
    while curr not in visited:
        visited.add(curr)
        cycle.append(curr)
        curr = a[curr]
    if k < len(visited):
        return cycle[k]
    cycle_start = cycle.index(curr)
    k -= cycle_start
    cycle = cycle[cycle_start:]
    return cycle[k % len(cycle)]


if __name__ == "__main__":
    n, k = map(int, input().split())
    a = [int(x) - 1 for x in input().split()]
    print(solve(a, k) + 1)

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


def read():
    N, K = map(int, input().strip().split())
    A = list(map(int, input().strip().split()))
    return N, K, A


def solve(N, K, A, INF = 10**8):
    counts = [0 for i in range(N)]
    a = 1
    loop_init = -1
    loop_count = -1
    while True:
        counts[a-1] += 1
        if counts[a-1] == 2 and loop_count < 0:
            loop_count = 0
        elif counts[a-1] == 3:
            loop_count += 1
            break
        elif loop_count >= 0:
            loop_count += 1
        a = A[a-1]
    loop_init = sum([c == 1 for c in counts])

    a = 1
    if loop_init > K:
        for i in range(K):
            a = A[a-1]
    else:
        loop_k = (K - loop_init) % loop_count
        for i in range(loop_init + loop_k):
            a = A[a-1]
    return a


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Solution (Python):
n, k = map(int,input().split())
a = list(map(int,input().split()))
li = [[] for i in range(n)]
step = 0
li[0].append(step)
pos = 1
noLoop = True

while k > 0:
    pos = a[pos - 1]
    k -= 1
    if noLoop:
        step += 1
        li[pos - 1].append(step)
        if len(li[pos - 1]) == 2:
            loop = li[pos - 1][1] - li[pos - 1][0]
            k %= loop
            noLoop = False
print(pos)