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
import numpy as np

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

tele = list(input().split())
tele = np.array([int(tele[i]) for i in range(N)])
seen = set([])
roop_in = deque([])
now = 1
w_num = 0

while now not in seen and w_num < K:
    seen.add(now)
    roop_in.append(now)
    now = tele[now - 1]
    w_num += 1

if w_num == K:
    print(now)
else:
    roop_in_index = roop_in.index(now)
    roop = list(roop_in)[roop_in_index:]
    roop_len = len(roop)
    last = (K - (w_num - 1)) % roop_len
    print(roop[last - 1])

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

used = [False]*(N+1)
ls = []
key = []
k = 1
while True:
    ls.append(k)
    used[k] = True
    k = Als[k]
    if used[k]== True:
        key.append(k)
        break


kind= ls.index(key[0]) 
if K <= kind:
    print(ls[K])
else:
    K = K - kind
    ls = ls[kind:]
    mn = K % len(ls)
    print(ls[mn])

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

N, K = map(int,input().split())
A = list(map(int, input().split())) 
check = [0]*N
tele_lis = []
start = []
def tele(x):
    check[x-1] = 1
    tele_lis.append(x)
    if check[A[x-1]-1] == 0:
        tele(A[x-1])
    else:
        start.append(A[x-1])
        return
tele(1)
for i in range(N):
    if start[0] == tele_lis[i]:
        break
if i >= K:
    print(tele_lis[K])
else:
    print(tele_lis[i::][(K-i) % (sum(check)-i)])

Solution (Python):
import collections

def main():
    n, k = map(int, input().split())
    a = [int(i) - 1 for i in input().split()]
    ans = solve(n, k, a)
    print(ans)


def solve(n, k, a):
    arrived = [-1 for i in range(n)]
    path = collections.deque()

    cnt = 0
    pos = 0
    path.append(pos)
    arrived[pos] = cnt

    while True:
        cnt += 1
        pos = a[pos]
        if arrived[pos] != -1:
            break
        arrived[pos] = cnt
        path.append(pos)
        if cnt == k:
            return pos + 1

    while True:
        if path[0] == pos:
            break
        path.popleft()

    
    

    path = list(path)
    k -= arrived[pos]

    ans = path[k % len(path)]

    return ans + 1


if __name__ == '__main__':
    main()

Solution (Python):

import sys
import math
from bisect import bisect_left, bisect_right, insort_left, insort_right
from collections import defaultdict, deque, Counter
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from heapq import heappop, heappush
from itertools import accumulate, groupby, product, permutations, combinations, combinations_with_replacement
from math import ceil, floor, factorial, log, sqrt, sin, cos
from operator import itemgetter
from string import ascii_lowercase, ascii_uppercase, digits
sys.setrecursionlimit(10**6)
INF = float('inf')
MOD = 10 ** 9 + 7
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(rs())
def rf(): return float(rs())
def rs_(): return [_ for _ in rs().split()]
def ri_(): return [int(_) for _ in rs().split()]
def rf_(): return [float(_) for _ in rs().split()]
def divisors(n, sortedresult=True):
    div = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            div.append(i)
            if i != n // i:
                div.append(n//i)
    if sortedresult:
        div.sort()
    return div

N, K = ri_()
A = ri_()
d = [0] * N
d[0] = 1
cnt = 1
loop = 0
now = 0
while True:
    now = A[now] - 1
    if d[now]:
        loop = cnt - d[now] + 1
        break
    else:
        cnt += 1
        d[now] = cnt
ans = 0
for i in range(N):
    if d[i] == min(d[now] + (K - cnt) % loop, K + 1):
        ans = i + 1
print(ans)

Solution (Python):



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


visit_list = [0]*N
visit_list[0] = 1
pos = a_nums[0]
visit_count = 1

while visit_list[pos-1]==0 and visit_count<K:
    visit_count += 1
    visit_list[pos-1] = visit_count
    pos = a_nums[pos-1]
visit_count += 1


if visit_count<K:
    tmp_1 = 0
    if pos==1:
        tmp_1 = visit_count - visit_list[pos-1] 
    else:
        tmp_1 = visit_count - visit_list[pos-1]
    tmp_2 = (K-visit_count) % tmp_1 
    
    for i in range(tmp_2+1):
        pos = a_nums[pos-1]


print(pos)

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

def main():
    n, k = map(int, input().split())
    a = [0]
    ta = list(map(int, input().split()))
    a += ta
    kaiten = [0] * (n + 1)
    count = 0
    koko = 1
    kaitenkikan = 0
    while k > 0:
        koko = a[koko]
        count += 1
        k -= 1
        if kaiten[koko] > 0:
            kaitenkikan = abs(count - kaiten[koko])
            break
        else:
            kaiten[koko] = count
    if k == 0:
        print(koko)
        sys.exit()
    k_remain = k % kaitenkikan
    if k_remain < 0:
        k_remain += kaitenkikan

    while k_remain > 0:
        koko = a[koko]
        k_remain -= 1

    print(koko)

if __name__ == '__main__':
    main()

Solution (Python):
n,k=map(int,input().split())
a=list(map(lambda x:int(x)-1,input().split()))
lst=[0]
now=0
memo=0
town=[0]*n
town[0]=1
b=0
for i in range(k):
	now=a[now]
	if town[now]==1:
		memo=now
		b=1
		break
	lst.append(now)
	town[now]=1
if b==1:
	i=lst.index(memo)
	l=len(lst)
	if memo!=0:
		lst=lst[i:]
		l-=len(lst)
		print(lst[(k-l)%len(lst)]+1)
	else:
		print(lst[k%l]+1)
else:
	print(now+1)

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

flag = [0 for _ in range(N)]

tmp = 1
i = 1
flag[0] = 1
while(True):
    tmp = A[tmp-1]
    i += 1
    if (flag[tmp-1] != 0):
        break
    flag[tmp-1] = i

pre = flag[tmp-1] - 1
cyc = i - flag[tmp-1]
if (K >= pre):
    index = (K - pre) % cyc
    if (index == 0):
        print(A[flag.index(pre + cyc)])
    else:
        print(A[flag.index(pre+index)])
else:
    print(A[flag.index(K)])

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

visited = [-1] * N
visited[0] = 0
nxt = 1
cycl = N
m = 0
for i in range(N):
    nxt = A[nxt-1]
    if visited[nxt-1] == -1:
        visited[nxt-1] = i+1
    else:
        cycl = i + 1 - visited[nxt-1]
        m = visited[nxt-1]
        break
if K < m: k = K
else:
    k = (K - m) % cycl + m

for i in range(N):
    if visited[i] == k:
        print(i+1)
        break

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

if K >= 2*N:
    point = 0
    L = [0 for _ in range(N)]
    loop = []
    for i in range(N+1):
        L[point] +=1
        T = 1
        if L[point] == 2:
            loop.append(point)
            p = point
            for j in range(N+1):
                point = A[point]
                if point != p:
                    loop.append(point)
                else:
                    T = 0
                    break
        if T == 1:
            point = A[point]
        else:
            break
    c = 0
    p = 0
    for i in range(N):
        if p != loop[0]:
            c+=1
            p = A[p]
        else:
            break
    J = K-c
    n = len(loop)
    k = J%n
    print(loop[k]+1)
else:
    point = 0
    for i in range(K):
        point = A[point]
    print(point+1)

Solution (Python):
from sys import stdin
import sys

N, K = [int(x) for x in stdin.readline().rstrip().split()]
A = list(map(int, input().split()))
B = [i for i in range(1, N+1)]
d = dict(zip(B, A))
t = [0 for i in range(N)]
d1 = dict(zip(B, t))
temp = 1
cnt = 0
ans = []
for i in range(K):
    d1[d[temp]] = d1.get(d[temp], 0)+1
    if d1.get(d[temp], 0) == 2:
        cnt += 1
        ans.append(d[temp])
        
    if d1.get(d[temp], 0) == 3:
        break
    temp = d[temp]
    if i == K-1:
        print(temp)
        sys.exit()
cnt1 = 0
for i, v in enumerate(d1):
    if d1[v] == 1:
        cnt1 += 1

k = K-1-cnt1
print(ans[k % cnt])

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

visited = [1] + [0]*(n-1)
idx = [0] + [-1]*(n-1)
route = [0]
while True:
    now = a[route[-1]]
    if visited[now]:
        break
    visited[now] = 1
    idx[now] = len(route)
    route.append(now)

border = idx[a[route[-1]]]
non_loop = route[:border]
loop = route[border:]

print(non_loop[k]+1) if k < len(non_loop) else print(loop[(k-len(non_loop))%len(loop)]+1)

Solution (Python):
import bisect
N,K=map(int,input().split())
A=list(map(int,input().split()))
index=[0]
index.append(A[0]-1)
tt=[A[0]-1]
flag=0
count=0
for _ in range(1,K):
    t=index[-1]
    ttt=bisect.bisect_left(tt, A[t]-1)

    if len(tt) > ttt and tt[ttt]==A[t]-1:
        index.append(A[t]-1)
        flag=1
        break
    index.append(A[t]-1)
    bisect.insort(tt,A[t]-1)
if flag==0:
    print(index[-1]+1)
    exit()


check = index[-1]
for i,c in enumerate(index):
    if c==check:
        a_path=i
        break
K-=a_path
t=len(index)-1-a_path
print(index[a_path+K%t]+1)

Solution (Python):
N, K = map(int, input().split())
A = list(map(lambda x: x-1, map(int, input().split())))
T = [False]*N

initcount = 0
count = 0
cur = 0
for _ in range(N):
    count += 1
    T[cur] = True
    cur = A[cur]
    if T[cur]:
        break
initcur = 0
for _ in range(count+1):
    initcount += 1
    initcur = A[initcur]
    if initcur == cur:
        break
if count != initcount:
    count -= initcount

if K <= initcount:
    cur = 0
    for _ in range(K):
        cur = A[cur]
    print(cur+1)
else:
    K -= initcount
    count = K%count
    for _ in range(count):
        cur = A[cur]
    print(cur+1)

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

check = [-1] * n
now = 0
check[now] = 0
cnt = 0
while cnt < k:
    cnt += 1
    now = g[now]
    if check[now] != -1:
        sa = cnt - check[now]
        cnt = cnt + (k - cnt)//sa *sa
    else:
        check[now] = cnt
print(now+1)

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
A = [0] + A
c = {}
c[1] = 0
n = 0
k = 1
while c.get(A[k]) is None or c[A[k]] != 2:
    if c.get(A[k]) is None:
        c[A[k]] = 0
    else:
        c[A[k]] += 1
    n += 1
    k = A[k]

from collections import Counter
if n <= K:
    num = Counter(c.values())[2]
    sa = len(c)-num
    bbb = K - sa
    m = bbb % num
    abc = list(c.keys())
    abc = abc[sa:len(c)]
    print(abc[m])
else:
    a = 1
    for i in range(K):
        a = A[a]
    print(a)

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

city = [-1 for i in range(0,N,1)]
count = 0
nex_city = 0
city[0]=0
while True:
    city[nex_city] = count
    nex_city = A[nex_city]-1
    count+=1
    if city[nex_city] >= 0:
        break

X = city[nex_city]
Y = count - city[nex_city]

nex_city = 0
if K < X:
    for i in range(0,K,1):
        nex_city = A[nex_city]-1
    print(nex_city+1)
    exit()

nex_city = 0
for i in range(0,X+(K-X)%Y,1):
    nex_city = A[nex_city]-1
print(nex_city+1)

Solution (Python):
n,k = map(int,input().split())
a = list(map(int,input().split()))
x = [1]
y = [False]*n
i = 0
s = 0
t = 0
xa = x.append
while True:
  if y[i] == True:
    for j in range(len(x)):
      if i == x[j]-1:
        s = j
        t = len(x)-j-1
        break
    break
  else:
    y[i] = True
    xa(a[i])
    i = a[i]-1
if k < s:
  print(x[k])
  exit()
x = x[s:-1]
print(x[(k-s)%t])

Solution (Python):
n,k=map(int,input().split())
p=list(map(int,input().split()))
a=[0]+p
flag=0
bef=1
town=[1]
town_set=set(town)
cnt=0
while flag==0 and cnt<k:
    if not a[bef] in town_set:
        town.append(a[bef])
        town_set.add(a[bef])
        bef=a[bef]
    else:
        flag=1
        memo=a[bef]
        break
    cnt+=1
if cnt==k:
    print(bef)
    exit()
for j in range(len(town)):
    if town[j]==memo:
        num=j
        break
x=len(town)-num
y=(k-num)%x
print(town[num+y])

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

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

genzaiti=0
visited=[-1]*n
visited[0]=0
nikaime=0
for i in range(k):
    genzaiti=A[genzaiti]-1
    if visited[genzaiti]==-1:
        visited[genzaiti]=i+1 
    else:
        nikaime=i+1
        break

if nikaime==0:
    print(genzaiti+1)
else:
    k=k-nikaime 
    idx=[i for i, v in enumerate(visited) if v>=visited[genzaiti]]
    aaa=[]
    for i in idx:
        aaa.append([i,visited[i]])
    aaa.sort(key=lambda x:x[1])
    finalidx=k%len(aaa)
    
    print(aaa[finalidx][0]+1)

Solution (Python):
N, K = (int(x) for x in input().split())
list = list(int(x) for x in input().split())
now = 1
check = [0]*N
begin = 1
begin_len = 0
for i in range(N):
    check[now-1] = i
    now = list[now-1]
    
    if check[now-1] != 0:
        begin = now
        begin_len = check[now-1]
        loop = (i+1) - check[now-1]
        break



if K <= (begin_len+loop):
    now = 1
    for i in range(K):
        now = list[now-1]
else:
    now = begin
    Ka = (K-begin_len) % loop
    for i in range(Ka):
        now = list[now-1]
print(now)

Solution (Python):
inpl = lambda: list(map(int,input().split()))
N, K = inpl()
A = inpl()
for i in range(N):
    A[i] -= 1
P = dict()
k = 0
former = True
i = 1
while i <= K:
    if k in P.keys() and former:
        loop = i - P[k]
        K = i + (K-i) % loop
        former = False
    else:
        P[k] = i
    k = A[k]
    i += 1
else:
    print(k+1)

Solution (Python):



import sys

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in list(ss)]
ss2nnn = lambda ss: [s2nn(s) for s in list(ss)]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [i2s() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, K = i2nn()
    A = list(map(lambda a:a-1, i2nn()))
    B = [0]
    B_rev = [None] * N
    B_rev[0] = 0
    left = 0
    for _ in range(N):
        a = A[B[-1]]
        if B_rev[a] is not None:
            left = B_rev[a]
            break
        B_rev[a] = len(B)
        B.append(a)
    
    
    
    if K <= left:
        print(B[K] + 1)
        return
    p = (K - left) % (len(B) - left)
    print(B[left + p] + 1)
    return

main()

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

slowRunner = 0
fastRunner = 0
flag = 1
while slowRunner!=fastRunner or flag:
    flag = 0
    nextSlow = listA[slowRunner]-1
    r = listA[fastRunner]-1
    nextFast = listA[r]-1
    slowRunner = nextSlow
    fastRunner = nextFast

f = 0
slowR1 = 0
slowR2 = slowRunner
while slowR1!=slowR2:
    f+=1
    nextR1 = listA[slowR1]-1
    nextR2 = listA[slowR2]-1
    slowR1 = nextR1
    slowR2 = nextR2

nodeL = []
start = slowR1
s = slowR1
flag = 1
while s!=start or flag:
    flag = 0
    nodeL.append(s+1)
    next = listA[s]-1
    s = next

if k > f:
    amari = (k-f)%len(nodeL)
    print(nodeL[amari])
else:
    i = k
    r = 0
    while i > 0:
        next = listA[r]-1
        r = next
        i-=1
    print(r+1)

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

lm = [1] * (n + 1)
visited = [False] * (n + 1)
firstVst = [-1] * (n + 1)

cycle = n
start = k

for i in range(n):
    lm[i + 1] = la[lm[i] - 1]
    if not visited[lm[i] - 1]:
        visited[lm[i] - 1] = True
        firstVst[lm[i] - 1] = i
    else:
        cycle = i - firstVst[lm[i] - 1]
        start = min(start, firstVst[lm[i] - 1])

if cycle == n:
    start = 0





m = (k - start) % cycle


print(lm[start + m])

Solution (Python):
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
d=[0]
w=set([0])
x=0
for i in range(n):
    if a[x]-1 not in w:
        d.append(a[x]-1)
        w.add(a[x]-1)
        x=a[x]-1
    else:
        f=a[x]-1
        break


if k<len(d):
    print(d[k]+1)
else:
    x=k-len(d)
    y=d.index(f)
    z=len(d)-y
    
    
    print(d[y+x%z]+1)

Solution (Python):
N,S=list(map(int, input().split())) 
tele=list(map(int, input().split())) 
for i in range(N):
    tele[i]-=1
loop=[0]*N
order=[]
now=0
cnt=0
while loop[now]!=1:
    loop[now]=1
    order.append(now)
    cnt+=1
    now=tele[now]

looptime=0
i=0
for i in range(cnt):
    if order[i]==now:
        looptime=cnt-i
        break
mod=(S-i)%looptime
if S-i<0:
    print(order[S]+1)
else:
    if (mod+i==len(order)):
        print(order[i]+1)
    else:
        print(order[mod+i]+1)

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

if K <= 200000:
  i = 1
  for _ in range(K):
    i = A[i-1]
  print(i)
  exit()

visited = {1}
order = [1]

i = 1
for count in range(1, 200001):
  i = A[i-1]
  if i in visited:
    break
  else:
    visited.add(i)
  order.append(i)

idx = order.index(i)
order2 = order[idx:]

mod = (K+1-idx) % len(order2)

print(order2[mod-1])

Solution (Python):
n,k=map(int,input().split())
b=list(map(int,input().split()))
v=[None]*n
w=[0]*n
i,c=0,b[0]
while v[c-1] is None:
    w[i]=c
    v[c-1] = i
    i+=1
    c=b[c-1]

head = v[c-1]
loop = i-v[c-1]
if k-1 < head:
    print(w[k-1])
else:
    print(w[head + ((k-1-head)%loop)])

Solution (Python):
n,k = map(int,input().split())
l1 = list(map(int,input().split()))
l = list(i-1 for i in l1)
bit = list(0 for i in range(n))
bit[0] =1
mi = [0]
m = l[0]
er = 0
while er ==0:
  if bit[m]==1:
    a = mi.index(m)
    r = mi[a:]
    er  =1
  else:
    bit[m] = 1
    mi.append(m)
    m = l[m]
 
be = mi[:a]+r

if k< len(be):
  print(be[k]+1)
else:
  w = k-len(be)+1
  u = (w%len(r))-1
  print(r[u]+1)

Solution (Python):
def D():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    next = a[0]
    path = [1]
    visited = [True] + [False]*(n-1)
    while not visited[next-1]:
        k -= 1
        if k==0:
            print(next)    
            break
        path.append(next)
        visited[next-1] = True 
        next = a[next-1]
    if k!=0:
        cyclic = path[path.index(next):]
        print(cyclic[k%(len(cyclic))-1])

D()

Solution (Python):
from collections import deque

N, K = map(int, input().split())
A = list(map(int, input().split()))
stack = deque([])
passed = set()
town = 0
while town not in passed:
    passed.add(town)
    stack.append(town)
    town = A[town] - 1

if len(stack) > K:
    print(stack[K] + 1)
    import sys
    sys.exit()

tail = 0
while stack[0] != town:
    _ = stack.popleft()
    tail += 1

K -= tail
K += 1
tmp = K % len(stack)
if tmp == 0:
    tmp = len(stack)
print(stack[tmp - 1] + 1)

Solution (Python):
import sys
N, K = map(int, sys.stdin.readline().split())
A = list(map(int, sys.stdin.readline().split()))

x = A[0]
visited = [0] * N
visited[0] = 1
visited_num = [1]
for i in range(N):
    if visited[x - 1] == 1:
        b = i + 1
        break
    visited[x - 1] = 1
    visited_num.append(x)
    x = A[x - 1]
    
for j, p in enumerate(visited_num):
    if p == x:
        a = j
        
if K < a:
    ans = visited_num[K]
else:
    n = (K - a) % (b - a)
    ans = visited_num[a + n]
    
print(ans)

Solution (Python):
import sys
import numpy

n,k=map(int,input().split())
a=list(map(int,input().split()))
b=numpy.zeros(n,dtype=int)

city=1
count=0
while b[city-1]==0:
    count+=1
    b[city-1]=1
    
    city=a[city-1]


if k<count:
    cc=1
    for i in range(k):
        cc=a[cc-1]
    print(cc)
    sys.exit()

c=1
cnt=0
while c!=city:
    cnt+=1
    c=a[c-1]

loop=count-cnt

d=(k-count)%loop

for i in range(d):
    city=a[city-1]

print(city)

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

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

log = []
check = [False]*N

def func(x, iter):
    x = A[x-1]

    if iter+1 == K:
        return x
    if check[x-1]:
        ix = log.index(x)
        loop = log[ix:]
        tmp = (K-iter-1)%len(loop)
        return loop[tmp]
    else:
        log.append(x)
        check[x-1] = True
        iter += 1
        return func(x, iter)

print(func(1, 0))

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

visited=[0]*N
ima_pos=0
mirai_pos=0

count_first=0
first_DP=[]
while(visited[ima_pos]==0):
  visited[ima_pos]=1
  mirai_pos=A[ima_pos]-1
  ima_pos=mirai_pos
  first_DP.append(ima_pos)
  count_first+=1

second_start=ima_pos
count_second=0
second_DP=[]

while(True):
  visited[ima_pos]=2
  mirai_pos=A[ima_pos]-1
  ima_pos=mirai_pos
  second_DP.append(ima_pos)
  count_second+=1
  if ima_pos==second_start:
    break


if K<=count_first:
  print(first_DP[K-1]+1)
elif K>count_first:
  cc=K-count_first
  if cc%count_second==0:
    print(second_DP[-1]+1)
  else:
    print(second_DP[cc%count_second-1]+1)

Solution (Python):
s = input().split()

n = int(s[0])
k = int(s[1])

a = input().split()

siyouzumi = {1}
y = [1]
t = 1

for i in range(1,k+1):

    t = int(a[t-1])
    if t in siyouzumi:
        haba = i - y.index(t)
        kaisu = int((k - i) / haba)

        l = k - (i + (haba * kaisu))

        for j in range(l):
            t = int(a[t-1])
        break

    siyouzumi.add(t)
    y.append(t)


print(t)

Solution (Python):
import sys
a,b=map(int,input().split())
b=b+1
l=[0]*(a)
List=list(map(int,input().split()))
i=0
j=1
while l[i]==0 and j<b:
  l[i]+=j
  j+=1
  i=List[i]-1
if j==b:
  print(i+1)
  sys.exit()
roop=j-l[i]
c=(b-j)%roop
for y in range(len(l)):
  if l[y]==c+l[i]:
    print(y+1)
    sys.exit()

Solution (Python):
def main():
    n, k = [int(x) for x in input().split()]
    teleporter = [int(x) - 1 for x in input().split()]
    route = []
    route_append = route.append
    seen = [False] * n
    traveled, now_i = 0, 0

    while traveled < n + 100:
        if seen[now_i]:
            
            break
        route_append(now_i)
        seen[now_i] = True
        now_i = teleporter[now_i]
        traveled += 1

    
    
    
    intro_length = route.index(now_i)
    loop_length = len(route) - intro_length
    if k >= intro_length:
        arriving_i = intro_length + (k - intro_length) % loop_length
    else:
        
        arriving_i = k
    return route[arriving_i] + 1


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

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = [-1 for _ in range(n)]

curr = 0
cnt = 0
k += 1
while k > 1:
  if b[curr] != -1:
    loop = cnt - b[curr]
    break
  b[curr] = cnt
  cnt += 1
  k -= 1
  curr = a[curr] - 1

if k != 1:
  mod = k % loop
  for i in range((mod-1) % loop):
    curr = a[curr] - 1

print(curr + 1)

Solution (Python):
S=lambda:input()
I=lambda:int(input())
L=lambda:list(map(int,input().split()))
LS=lambda:list(map(str,input().split()))

def main():
    import sys
    input = sys.stdin.readline
    n,k=L()
    a=L()
    visited=[0]*(n+1)
    tmp=0
    now=0
    visited[0]=1
    loopat=-1
    for i in range(k):
        
        tmp=i+2
        now=a[now]-1
        
        
        if visited[now]==0:
            visited[now]=i+2
        else:
            loopat=now
            break
    
    
    
    if loopat==-1:
        print(now+1)
        exit()
    elif tmp-visited[loopat]==0:
        tmp2=k
        dist=1
        now=0
    else:
        tmp2=(k-(visited[loopat]-1))%(tmp-visited[loopat])
        dist=loopat+1
    
    
    
    
    for i in range(tmp2):
        now=a[now]-1
        dist=now+1
        
    
    print(dist)
    
    
if __name__ == '__main__':
    main()

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)

int1 = lambda x: int(x) - 1


def II(): return int(input())


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


def MI1(): return map(int1, input().split())


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


def LI1(): return list(map(int1, input().split()))


def LLI(rows_number): return [LI() for _ in range(rows_number)]


def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))


INF = float('inf')


def solve():
    n, k = MI()
    A = LI1()
    
    memo = {0: 0}
    current = 0
    keiro = []
    for i in range(n):
        keiro.append(current)
        next = A[current]
        
        if (i + 1) == k:
            print(next+1)
            return

        if memo.get(next, -1) == -1:
            memo[next] = i + 1
            current = next
        else:
            pre = current
            current = next
            keiro.append(current)
            
            left = k - i - 1
            
            loopsize = memo[pre] - memo[current] + 1
            
            r = left % loopsize
            
            
            
            ans = keiro[memo[current] + r] + 1
            print(ans)
            return


if __name__ == '__main__':
    solve()

Solution (Python):
from collections import defaultdict
from sys import stdin


def main():
    input = lambda: stdin.readline()[:-1]
    N, K = map(int, input().split())
    A = list(map(int, input().split()))

    a, i = [1], 0
    for _ in [0] * N:
        a.append(A[i])
        i = A[i] - 1

    if K <= N:
        print(a[K])
        return

    n = defaultdict(list)
    for i, v in enumerate(a):
        if n[v]:
            n[v].append(i)
            break
        n[v].append(i)
    l, r = n[v][0], n[v][1]
    loop = a[l:r]
    K -= l
    n = K % (r - l)
    print(loop[n])


main()

Solution (Python):
import itertools

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



loopstart = -1
loopend = -1
path = []
nextcity = 0
FLAGS = [False for _ in range(N)]
for i in range(N):
    currentcity = nextcity
    path.append(nextcity)
    FLAGS[nextcity] = True
    nextcity = A[nextcity]-1
    if FLAGS[nextcity]:
        loopstart = nextcity
        loopend = currentcity
        path.append(nextcity)
        break



toloop = path.index(loopstart)


looplength = path.index(loopend) - toloop + 1



if K < toloop + looplength + 1:
    print(path[K] + 1)
else:
    fromloopstart = (K - toloop) % looplength
    print(path[toloop + fromloopstart] + 1)

Solution (Python):
def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    cycle = 0
    flag = True
    visited = [0] * N
    visited[0] = 1
    visited_num = [0] * N
    before_city = 0
    visited_city = 0
    periodic = 0
    while flag:
        next_city = A[before_city] - 1
        cycle += 1
        if cycle >= K:
            flag = False
        if visited[next_city] == 1:
            visited_city = next_city
            periodic = cycle - visited_num[next_city]
            flag = False
        else:
            visited[next_city] = 1
            visited_num[next_city] = cycle
            before_city = next_city
    
    
    if cycle < K:
        K_new = (K - cycle) % periodic
        before_city = visited_city
        for i in range(K_new):
            next_city = A[before_city] - 1
            before_city = next_city
        print(next_city+1)
    else:
        print(next_city+1)

if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np

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

if a[0] == 1:
  print(1)
  exit()
  
log = np.full(n, -1)
log[0] = 0
step = 0
now = 0
flag = 0
while step < k:
  now = a[now] - 1
  step += 1
  if log[now] != -1:
    flag = 1
    break
  else:
    log[now] = step

if flag == 0:
  print(now+1)
  exit()

loop = step - log[now]
remain = k - step
if remain > loop:
  remain = remain % loop

for i in range(remain):
  now = a[now] - 1
print(now+1)

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
A=[i-1 for i in A]
c=A[A[0]]
 
s=set()
s.add(0)
s.add(A[0])
I=[]
I.append(0)
I.append(A[0])

while True:
  if c in s:
    break
  s.add(c)
  I.append(c)
  c=A[c]

a=I.index(c)
if K>=a:
  K-=a
else:
  ans=0
  for i in range(K):
    ans=A[ans]
  print(ans+1)
  exit()

ans=0
for i in range(a):
  ans=A[ans]

mod=len(s)-a
K%=mod

if K==0:
  print(ans+1)
  exit()




for i in range(K):
  ans=A[ans]
print(ans+1)

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

X = [-1] * N
i = 0
t = 0
while X[i] < 0:
    X[i] = t
    i = A[i]
    t += 1

X[i] + (K - X[i]) % (t - X[i])

if K <= X[i]:
    print(X.index(K) + 1)
else:
    print(X.index(X[i] + (K - X[i]) % (t - X[i]) ) + 1)

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




trace = [0]*N
loop_start = 0
loop_before = 0
cnt = 0
all_cnt = 0

if K > N:
    loop = 0
    now = 0
    while(1):
        
        trace[now] += 1
        if trace[now] == 3:
            break
        if trace[now] == 2:
            cnt += 1
            loop += 1 
            if cnt == 1: 
                loop_start = now
                loop_before = all_cnt
        now = A[now]-1
        all_cnt += 1

    loop_before = loop_before - loop 

    
    
    
    
    min_K = (K-1-loop_before) % loop
    
    
    now = 0
    for i in range(loop_before):
        now = A[now]-1
    for i in range(min_K):
        now = A[now]-1
    print(A[now])

if K <= N:
    now = 0
    for i in range(K-1):
        now = A[now]-1
    print(A[now])

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

    p_bool = [False] * n
    ne_p = 1
    p_bool[ne_p-1] = True
    step = 0
    for i in range(n):
        ne_p = a[ne_p-1]
        step += 1
        if p_bool[ne_p-1]:
            break
        else:
            p_bool[ne_p-1] = True
        if step == k:
            print(ne_p)
            sys.exit()
    
    p_list = []
    sta = ne_p
    for i in range(n):
        ne_p = a[ne_p-1]
        step += 1
        p_list.append(ne_p)
        if ne_p == sta:
            break
        if step == k:
            print(ne_p)
            sys.exit()

    len_l = len(p_list)
    left = k-step
    left -= (left//len_l) * len_l
    print(p_list[left-1])
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
        
    
    
    
    
    
    
    
    
    
    
    
    

solve()

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

a = list(map(int, input().split()))
done = [0]*n
stay = 1

for i in range(1, k+1):
    if done[stay-1] != 0:
        break
    done[stay-1] = i
    stay = a[stay-1]

nokori = k + 1 - i
if nokori != 1:
    loop = i - done[stay-1]
    for i in range(nokori%loop):
        stay = a[stay-1]

print(stay)