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):
n,k=map(int,input().split())

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

visited=[0]*(n+1)
visited[1]=1

now=1
loop=0
isloop=0
for i in range(k):
  
  if visited[a[now]]>0:
    loop=visited[now]-visited[a[now]]+1
    now=a[now]
    isloop=1
    k-=i+1
    break
  
  visited[a[now]]=visited[now]+1
  now=a[now]
  

ans=now
if isloop:
  k%=loop
  
  for i in range(k):
    now=a[now]
  
print(now)

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


visited = [-1] * (N+1)

visited[1] = 0

i = 1
k = 0
while True:
    nv = A[i]
    k += 1
    if K == k:
        print(nv)
        exit()
    if not visited[nv] == -1:
        break
    visited[nv] = k
    i = nv

loop = k - visited[nv]
res = (K-visited[nv]) % loop

for i in range(res):
    nv = A[nv]

print(nv)

Solution (Python):
def resolve():
    N,K = map(int,input().split())
    A = [int(i)-1 for i in input().split()]
    visited =[False]*N
    steps = [K for i in range(N)]

    current = 0
    while True:

        if K == 0:
            print(current+1)
            return
        if not visited[current]:
            visited[current]=True
            steps[current]=K
            current=A[current]
            K-=1
        else:
            K= K % (steps[current]-K)
            break
    
    while K != 0:

        current= A[current]
        K-=1
    print(current+1)




if __name__ == "__main__":
    resolve()

Solution (Python):
n,k = map(int,input().split())
a = [0]+list(map(int,input().split()))
memory = [1]
dic = {}
cur = 1
count = 0
while True:
    if count == k:
        print(cur)
        exit()
    if a[cur] in dic.keys():
        loop_begin = dic[a[cur]]
        loop_end = count
        break
    else:
        count += 1
        memory.append(a[cur])
        dic[a[cur]] = count
        cur = a[cur]
loop = memory[loop_begin:]
loop_length = loop_end-loop_begin+1
k -= loop_begin
print(loop[k%loop_length])

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n,k=MI()
    aa=LI1()
    pos=[-1]*n
    i=aa[0]
    pos[0]=0
    log=[0]
    j=1
    while pos[i]==-1:
        log.append(i)
        if j==k:
            print(log[-1]+1)
            exit()
        pos[i]=j
        i=aa[i]
        j+=1
    pre=pos[i]
    k-=pre
    t=len(log)-pre
    k%=t
    print(log[pre+k]+1)

main()

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
roop = [1]
roop2 = set([1])
while True:
    next_i = a[roop[-1] - 1]
    if next_i in roop2:
        break
    else:
        roop.append(next_i)
        roop2 |= set([next_i])
temp = roop.index(next_i)
if k <= temp:
    print(roop[k])
else:
    period = len(roop) - temp
    temp2 = (k - temp) % period
    print(roop[temp + temp2])

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

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

pos = 1

seen = {}
seen[1] = 1

count = 0

ans = 0
loop_pos = 0

for i in range(n):
    pos -= 1
    next_pos = As[pos]
    pos = next_pos
    count += 1
    if count == k:
        ans = next_pos
        break
    elif seen.get(next_pos, None) is None:
        seen[next_pos] = 1
    else:
        loop_pos = next_pos
        break

if ans != 0:
    print(ans)
else:
    k -= count
    count = 0
    for i in range(n):
        pos -= 1
        next_pos = As[pos]
        pos = next_pos
        count += 1
        if count == k:
            ans = next_pos
            break
        elif next_pos == loop_pos:
            break

    if ans != 0:
        print(ans)
    elif k % count == 0:
        print(loop_pos)
    else:
        k = k % count
        count = 0
        for i in range(n):
            pos -= 1
            next_pos = As[pos]
            pos = next_pos
            count += 1
            if count == k:
                ans = next_pos
                break

        print(ans)

Solution (Python):
from math import floor,ceil,sqrt
import fractions
import collections
import itertools
from collections import deque
N,K=map(int,input().split())
A=list(map(int,input().split()))
trail=[0]*N
trail[0]=1
buf=0
firstonly=[]
loop=[]

cnt=0
while True:
    nxt=A[buf]-1
    if trail[nxt]<2:
        trail[nxt]=trail[nxt]+1
        cnt=cnt+1
    else:
        break
    buf=nxt
    
    

buf=0
if trail[buf]==1:
    firstonly.append(buf)
else:
    loop.append(buf)
i=0
while i<cnt:
    nxt=A[buf]-1
    if trail[nxt]==1:
        firstonly.append(nxt)
    else:
        loop.append(nxt)
    i=i+1
    buf=nxt
    
    

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

Solution (Python):
def main():
    import sys
    sys.setrecursionlimit(10**6)
    input = sys.stdin.readline
    N, K = [int(x) for x in input().strip().split()]
    A = {i:int(x) for i, x in enumerate(input().strip().split(), start=1)}
    dic = {}
    p = 1
    cnt = 0
    dic[p] = cnt
    while K > 0:
        p = A[p]
        cnt += 1
        K -= 1
        if p in dic:
            K %= (cnt - dic[p])
        else:
            dic[p] = cnt

    print(p)

if __name__ == '__main__':
    main()

Solution (Python):
n,k = map(int,input().split())
ans = [1]
gone = [0] * n
now = 0
cnt = 0
lis = list(map(int,input().split()))
while True:
    if cnt == k:
        print(ans[k])
        exit()
    gone[now] = 1
    if gone[lis[now]-1] == 0:
        gone[lis[now]-1] = 1
        now = lis[now]-1
        ans.append(now+1)
    else:
        num = len(ans)
        now = lis[now]
        first = ans.index(now)
        k -= first
        k %= (num-first)
  
  
  
        print(ans[first+k])
        exit()
    cnt += 1

Solution (Python):
n,k = map(int, input().split())
a = list(map(int, input().split()))
a.insert(0,0)
now = 1
seen = [0]*(n+1)
seen[1] = 1
for i in range(1,n+1):
  now = a[now]
  if seen[now] != 0:
    break
  else:
    seen[now] = i+1
if k <= max(seen):
  print(a[seen.index(k)])
elif (k - max(seen)) % (max(seen)-seen[now]+1) == 0:
  print(a[seen.index(max(seen))])
else:
  print(a[seen.index(max(seen) - (max(seen)-seen[now]+1) + (k - max(seen)) % (max(seen)-seen[now]+1))])

Solution (Python):
def resolve():
    n, k = map(int, input().split())
    a = [int(x) - 1 for x in input().split()]
    dist = [-1] * n
    dist[0] = 0
    now = 0
    road = [0]
    while True:
        nxt = a[now]
        if dist[nxt] < 0:
            dist[nxt] = dist[now] + 1
            now = nxt
            road.append(now)
        else:
            first = dist[now] + 1
            roop = first - dist[nxt]
            break
    if k < first:
        print(road[k] + 1)
        return
    k -= first - roop
    k %= roop
    print(road[first - roop + k] + 1)


if __name__ == '__main__':
    resolve()

Solution (Python):
N, K = map(int,input().split())
A = list(map(int, input().split()))
dic = {1:0}
now = 1
flag = 0
T = 0
log = [1]
for i in range(K):
  now = A[now-1]
  
  if now in dic:
    flag=1
    T=i+1-dic[now]
    log = log[dic[now]:]
    break
  dic[now] = i+1
  log.append(now)
if flag!=1:
  print(now)
else:
  print(log[(K-dic[now])%T])

Solution (Python):




def main():
    
    N,K = map(int,input().split())
    A = list(map(int,input().split()))
    slow = 0
    fast = 0
    collide = -1
    while True:
        slow = A[slow]-1
        fast = A[A[fast]-1]-1
        if slow == fast:
            collide = slow
            break
    
    slow = 0
    fast = collide
    begin = 0
    while True:
        if slow == fast:
            break
        slow = A[slow]-1
        fast = A[fast]-1
        begin += 1
    
    loopC = 0
    while True:
        slow = A[slow]-1
        fast = A[A[fast]-1]-1
        loopC+=1
        if slow == fast:
            break
    
    if begin >=K:
        current = 0
        for i in range(K):
            current = A[current]-1
        print(current+1)
    else:
        K -= begin
        current = 0
        for i in range(begin):
            current = A[current] - 1
        for i in range(K%loopC):
            current = A[current]-1
        print(current+1)
    pass

if __name__ == '__main__':
    main()

Solution (Python):


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

footprint_L = list()
footprint_S = set()
i = 0
footprint_S.add(i)
footprint_L.append(i)
while cities[i] not in footprint_S:
    footprint_S.add(cities[i])
    footprint_L.append(cities[i])
    i = cities[i]




cyclestart = footprint_L.index(cities[i])
cyclelen = len(footprint_L) - cyclestart



if k >= len(footprint_L):
    print(footprint_L[cyclestart+(k-cyclestart) % cyclelen]+1)
else:
    print(footprint_L[k]+1)

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

visited = [False]*(N)
visited[0] = True

dist = [0]*N
cur = 0
idx = 1
result = [0]
while True:
    nxt = A[cur]
    if visited[nxt]:
        amari = dist[nxt]
        MOD = idx - amari
        break
    else:
        visited[nxt] = True
        dist[nxt] = idx
        cur = nxt
        idx += 1
        result.append(cur)

if K<=amari:
    ans = result[K]+1
else:
    K -= amari
    result = result[amari:]
    ans = result[K%MOD]+1
print(ans)

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

visited = [0 for _ in range(n)]
i = 0
while visited[i] == 0:
    visited[i] = 1
    i = a[i]

cnt = 0
goal = i
i = goal
while not (i == goal and cnt > 0):
    i = a[i]
    cnt += 1

i = 0

if True:
    while i != goal and k > 0:
        k -= 1
        i = a[i]
    if k != 0:

        k = k % cnt
        i = goal

        for cnt in range(k):
            i = a[i]

print(i+1)

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

visited_city = {1: 0}
visited_city_inv = {0: 1}

now = 1
num = 0
while True:
    next_city = arr[now - 1]
    num += 1
    if next_city not in visited_city:
        visited_city[next_city] = num
        visited_city_inv[num] = next_city
        now = next_city
    else:
        break

if k < num:
    ans = visited_city_inv[k]
else:
    x = visited_city[next_city]
    period = num - x
    ans = visited_city_inv[x + (k - x) % period]

print(ans)

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


tlist=[]
pos=1
pos_set=set()
while True:
  tlist.append(pos)
  if pos in pos_set:
    break
  pos_set.add(pos)
  pos=alist[pos]
  
dup_pos2=len(tlist)-1
dup_pos1=-1
for i in range(len(tlist)):
  if tlist[i]==tlist[-1]:
    dup_pos1=i
    break
    

cycle=dup_pos2-dup_pos1

if K<len(tlist):
  print(tlist[K])
else:
  print(tlist[(K-dup_pos1)%cycle+dup_pos1])

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
R = {1:0}
i, t = A[0], 1

while K > t:
    r = R.get(i)
    if r == None:
        R[i] = t
        i = A[i-1]
        t += 1
    else:
        K -= r
        K %= t - r
        for k in range(K):
            i = A[i-1]

print(i)

Solution (Python):

import sys
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return map(int,input().split())
def LI(): return list(map(int,input().split()))

def main():
    N,K = MAP()
    A = LI()
    isVisited = set()
    loop = []
    cur = 0

    while True:
        if cur in isVisited:
            break
        isVisited.add(cur)
        loop.append(cur)
        cur = A[cur]-1
    
    before_loop = loop.index(cur)
    loop_length = len(loop)- before_loop

    if K < len(loop):
        print(loop[K]+1)
    else:
        print(loop[before_loop+(K-before_loop)%loop_length]+1)


    return

if __name__ == '__main__':
    main()

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



ans = 1
c = set()
c.add(1)
for i in range(k):
    ans = a[ans-1]
    if ans in c:
        break
    else:
        c.add(ans)
count = 0
tmp=1
for i in range(k):
    tmp = a[tmp-1]
    if tmp == ans:
        val = i +1
        break
k = k - val
if (len(c)- val) == 0:
    s = k % len(c)
else:
    s = k % (len(c) - val)

for i in range(s):
    tmp = a[tmp-1]

print(tmp)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
order = [-1]*N
crr = 0
T = 0
s = -1
order[0] = 0
for i in range(N+1):
    crr = A[crr] - 1
    if order[crr] >= 0:
        T = (i+1) - order[crr]
        s = order[crr]
        break
    order[crr] = i+1

if K <= s:
    crr = 0
    while(K):
        K -= 1
        crr = A[crr]-1
    print(crr+1)
else:
    k = K-s
    d = k % T
    while(d):
        d -= 1
        crr = A[crr]-1
    print(crr+1)

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
ok=set()
now=0
l=[]
while now not in ok and k:
    l.append(now)
    ok.add(now)
    now=a[now]-1
    k-=1
if k==0:print(now+1);exit()
length=len(ok)-(h:=l.index(now))
l=l[h:]

k=(k)%length

print(l[k]+1)

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

already = [-1 for i in range(n)]
already[0] = 0
mati = 0
num = 0
for _ in range(n):
    num += 1
    mati = a[mati]
    if already[mati] == -1:
        already[mati] = num
        continue
    else:
        roop = num - already[mati]
        break

saisho = already[mati]
if k <= saisho:
    tugi = 0
    for _ in range(k):
        tugi = a[tugi]
    print(tugi+1)
else:
    nokori = k - saisho
    amari = nokori % roop
    for _ in range(amari):
        mati = a[mati]
    print(mati+1)

Solution (Python):
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
c=[0 for i in range(n)]

l=1
u=0
f=True
while True:
  u+=1
  l=a[l-1]
  if u==k:
    print(l)
    f=False
  if c[l-1]:
    break
  else:
    c[l-1]=u
k=(k-(c[l-1]))%(u-c[l-1])
while k:
  k-=1
  l=a[l-1]
if f:
  print(l)

Solution (Python):


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

town_list = [-1,0]+[-1 for i in range(N-1)]
town_now = 1
n_teleport = 0

while n_teleport<K:
  n_teleport += 1
  town_now = A[town_now]
  if town_list[town_now]==-1:
    town_list[town_now] = n_teleport
  else:
    break

if n_teleport==K:
  print(town_now)
else:
  loop_start_town = town_now
  loop_start_time = town_list[town_now]
  loop_len = n_teleport-town_list[town_now]
  M = (K-loop_start_time)%loop_len
  for _ in range(M):
    town_now = A[town_now]
  print(town_now)

Solution (Python):

N,K=map(int,input().split())
A=list(map(int,input().split()))
used=[False for i in range(N)]
used[0]=True
p=1
L=[1]

for i in range(N+1):
    p=A[p-1]
    L.append(p)
    if used[p-1]:
        looper=p
        break
    used[p-1]=True

for i in range(len(L)):
    if L[-(2+i)]==looper:
        a=i+1
        b=len(L)-1-a
        break
if K>b:
    ans=L[b+(K-b)%a]
else:
    ans=L[K]

print(ans)

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

t_list = [1]
t_table = { 1: 0 }
t = 1
loop = None
while True:
	t = A_list[t - 1]
	if t in t_table:
		loop = t_table[t]
		break
	t_table[t] = len(t_list)
	t_list.append(t)

t_head = t_list[:loop]
t_loop = t_list[loop:]

if K < loop:
	print(t_head[K])
else:
	print(t_loop[(K - loop) % len(t_loop)])

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

visited = set()
visited.add(0)
now = 0
root = [-1 for i in range(n+1)]
root[0] = 0
ind = 1
cnt = 0
first_seen = {}
first_seen[0] = 0

finished = False
while True:
    goto = arr[now]-1
    
    if goto not in visited:
        visited.add(goto)
        now = goto
        root[ind] = goto
        ind += 1
        cnt += 1
        first_seen[goto] = cnt
    else:
        root[ind] = goto
        cnt += 1
        now = goto
        break

    if cnt == k:
        finished = True
        break

if finished:
    print(now+1)
else:
    
    
    pathl = cnt-first_seen[now]
    
    
    left = k-cnt
    left = left%pathl
    fin = first_seen[now] + left
    
    print(root[fin]+1)

Solution (Python):
N, K = map(int, input().split())
A = [0]
for a in map(int, input().split()):
    A.append(a)

if K <= N:
    now = 1
    for i in range(1, K+1):
        now = A[now]
    print(now)
else:
    check = [-1]*(N+1)
    check[1] = 0
    now = 1
    for i in range(1, N+1):
        now = A[now]
        if check[now] >= 0:
            first = check[now]
            second = i
            break
        else:
            check[now] = i
    now = 1
    for i in range(first):
        now = A[now]
    K = (K-first)%(second-first)
    for i in range(K):
        now = A[now]
    print(now)

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
c=0
d={}
d[1]=0
dd={}
dd[0]=1
now=1
while True:
    now=a[now-1]
    c+=1
    if now in d:
        break
    d[now]=c
    dd[c]=now
s=d[now]
if k<=s:
    print(dd[k])
    exit()
p=c-s
k-=s
k%=p
k+=s
print(dd[k])

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

ved = [-1]*n
ved[0] = 0
cur = 0
i = k
while i > 0:
  cur = ls[cur]
  i -= 1  
  if ved[cur] >= 0:
    i= i % ((k-i)-ved[cur])
  else:
    ved[cur] = k-i
print(cur+1)

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
dest = [1]
dest_set = {1}
now = 1
while True:
    nxt = a[now-1]
    if nxt in dest_set:
        loop = dest.index(nxt)
        break
    dest.append(nxt)
    dest_set.add(nxt)
    now = nxt
if k<len(dest):
    print(dest[k])
else:
    print(dest[(k-len(dest))%(len(dest)-loop)+loop])

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

city_position = {}
step = 0
city = 0

while city not in city_position:
	city_position[city] = step
	city = a[city]
	step += 1

steps_before_cycle = city_position[city]
cycle_len = step - steps_before_cycle



city = 0
for i in range(min(k, steps_before_cycle)):
	city = a[city]

k -= steps_before_cycle
if k > 0:
	k %= cycle_len

	for i in range(k):
		city = a[city]


print(city+1)

Solution (Python):
def main():
    n, k = map(int, input().split())
    a = list(map(lambda x: int(x)-1, input().split()))
    visited = [0]
    visited_set = {0}
    now = 0
    for i in range(2*n):
        now = a[now]
        if now in visited_set:
            break
        else:
            visited.append(now)
            visited_set.add(now)
    l = len(visited)
    v = visited.index(now)
    if k < v:
        print(visited[k]+1)
    else:
        k -= v
        k %= (l-v)
        k += v
        print(visited[k]+1)


main()

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
n = 1
B = [0]*N
state = 0
for i in range(2*N+1):
    if i == K:
        state = 1
        break
    B[n-1] = i+1
    n = A[n-1]
    if B[n-1] != 0:
        t = i+2
        break
if state:
    print(n)
else:
    c = t-B[n-1]
    s = (K+1-t)%c
    for i in range(s):
        n = A[n-1]
    print(n)

Solution (Python):
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
n,k=map(int,input().split())
l=list(map(int,input().split()))
a=1
s=set()
count=0
while a not in s:
	s.add(a)
	a=l[a-1]
	count+=1
	if count==k:
		print(a)
		exit()
if count<k:
	k-=count
	
else:
	a=1
	for i in range(k):
		a=l[a-1]
	print(a)
	exit()
s=set()
count=0
while a not in s:
	s.add(a)
	a=l[a-1]
	count+=1
if count<k:
	f=k%count
	for i in range(f):
		a=l[a-1]
	print(a)
else:
	for i in range(k):
		a=l[a-1]
	print(a)

Solution (Python):
def main():
    N, K = map( int, input().split())
    A = list( map( lambda x: int(x)-1, input().split()))
    T = [0]
    C = [-1]*N
    C[0] = 0
    s = 0
    count = 0
    while True:
        s = A[s]
        count += 1
        if count == K:
            print(s+1)
            return
        if C[s] != -1:
            L = count - C[s]
            break
        C[s] = count
        T.append(s)

    m = len(T) - L
    print( T[-L:][(K-m)%L]+1)
if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
MOD = 10**9+7


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

visited = dict()
rvs = dict()
cur = 0
num = 0
while True:
    if cur in visited:
        
        
        s = visited[cur]
        roop = num - s
        kk = (k-s)%roop
        
        print(rvs[kk+s]+1)
        exit()
    if num == k:
        print(cur+1)
        exit()
    else:
        visited[cur] = num
        rvs[num] = cur
        cur = A[cur]-1
        num += 1

Solution (Python):

import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


from collections import defaultdict


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = defaultdict(list)

    def add_edge(self, f, t, w=1):
        self.E[f].append((t, w))


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

    
    g = Graph(N)
    for X, Y in zip(range(1, N+1), A):
        g.add_edge(X-1, Y-1)

    seen = [False]*N
    prev = []
    state = 0

    while True:
        seen[state] = True
        prev.append(state)
        for dest, _ in g.E[state]:
            state = dest
        if seen[state]:
            break
    amari = prev.index(state)
    period = len(prev)-amari
    
    if K < amari:
        print(prev[K]+1)
    else:
        print(prev[amari + (K-amari) % period]+1)
    return


if __name__ == '__main__':
    main()

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






A = [a - 1 for a in A]
now = 0
V = [False for i in range(n)]
V[0] = 0
L = [now]
cnt = 0
while not V[A[now]]:
    cnt += 1
    now = A[now]
    L.append(now)
    V[now] = cnt
a = V[A[now]]
b = cnt - a + 1
if k < cnt:
    print(L[k] + 1)
    exit()
print(L[(k - a) % b + a] + 1)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
line = {}
for i in range(N):
  line[i+1] = A[i]

dp = [[0]*(N+1) for _ in range(71)]
for i in range(1, N+1):
  dp[0][i] = line[i]

for i in range(70):
  for j in range(1, N+1):
    dp[i+1][j] = dp[i][dp[i][j]]

for i in range(1, N+1):
  now = i 
  for j in range(70):
    
    if (K&(1<<j)) != 0:
      now = dp[j][now]

  print(now)
  exit()

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

c=1
path=[]
d={}
l=0
while l<=k:
    if c in d:
        p=d[c]
        
        pattern_l = l-p
        k-=((k-p)//pattern_l)*pattern_l
    path.append(c)
    l+=1
    d[c]=l-1
    c=A[c-1]
print(path[k])

Solution (Python):


def solve(N, K, A):
    ind = []
    tr = None
    visited = set()
    cur = 1
    while cur not in visited:
        ind.append(cur)
        visited.add(cur)
        cur = A[cur-1]
    tr = cur
    itr = ind.index(tr)
    if len(ind) > K:
        return ind[K]
    KK = K - itr
    iind = ind[itr:]
    return iind[KK%len(iind)]

        



def main():
    N, K = map(int, input().split())
    A = tuple(map(int, input().split()))
    print(solve(N, K, A))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10**6) 
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right

from collections import deque 


from collections import Counter

from itertools import accumulate

from heapq import heapify,heappop,heappush




def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)

def main():
    mod = 10**9+7
    

    
    N, K = map(int, input().split())
    A = tuple(map(int, input().split())) 
    
    
    p=0
    l=[-1]*N
    cl=[0]*N
    for i in range(N):
        l[i]=p
        cl[p]=1
        p=A[p]-1
        if cl[p]!=0:
            x=l.index(p)
            r=i+1-x
            break
        r=N
        x=0
    
    if K<=x:
        ans=l[K]
        print(ans+1)
    else:
        ans=l[x+(K-x)%r]
        print(ans+1)
    



if __name__ == "__main__":
    main()

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

pos = 1
move= 0
colors = [-1]*(n+1)

while(colors[pos]==-1):
    colors[pos] = move
    move += 1
    pos = a[pos]
    if move==k:
        print(pos)
        break
else:
    turn = move - colors[pos]
    rest = (k-colors[pos]) % turn
    while rest:
        pos = a[pos]
        rest -= 1
    print(pos)

Solution (Python):
from collections import deque

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

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

d = [-1] * N
d[0] = 0
q = deque()
q.append(1)

while(q):
    x = q.popleft()
    n = a[x - 1]
    if(d[n-1] == -1):
        d[n-1] = d[x-1] + 1
        q.append(n)

if(k <= max(d)):
    for i in range(N):
        if(d[i] == k):
            print(i+1)
            exit()


rS = n

d2 = [-1] * N
d2[rS - 1] = 0
q = deque()
q.append(rS)

while(q):
    x = q.popleft()
    n = a[x - 1]
    if(d2[n-1] == -1):
        d2[n-1] = d2[x-1] + 1
        q.append(n)
ma = max(d2) + 1
k -= d[rS - 1]
k %= ma

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

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

loop = [1]
now = 1
d = set([1])
for i in range(n):
    now = a[now]
    if now in d:
        for j in range(len(loop)):
            if now == loop[j]:
                ind = j
        break
    d.add(now)
    loop.append(now)

if len(loop) >= k+1:

    print(loop[k])

else:
    k -= ind
    loop = loop[ind:]
    print(loop[k%len(loop)])

Solution (Python):
import sys, os

def f():
    args = list(map(int,input().split()))
    if len(args) > 1:
        return args
    return args[0]

if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n,k  = f()
    A = f()

    A = [0] + A
    last = [-1] * (n+1)

    last[1] = 0
    cur= 1

    pos = -1
    cycle = -1

    if k < n:
        for i in range(k):
            cur = A[cur]
        print(cur)
    else:
        for i in range(n):
            nxt = A[cur]
            if  i == n-1:
                pos = nxt
                cycle = n-1 - last[nxt]
            last[nxt] = i
            cur = nxt
            

        steps = (k - n)%cycle
        cur = pos
        for i in range(steps):
            cur = A[cur]
        print(cur)

solve()

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, k = list(map(int, readline().split()))
    temp = [-1] + list(map(int, readline().split()))
    a = {i: temp[i] for i in range(1, n + 1)}

    cur = 1
    cnt = 0
    visited = {i: -1 for i in range(1, n + 1)}
    visited[1] = 0

    while True:
        cnt += 1
        cur = a[cur]
        if visited[cur] == -1:
            visited[cur] = cnt
        else:
            break

    start = cur
    st = visited[cur]
    gt = cnt
    period = gt - st
    t = k

    if t < st:
        cur = 1
        cnt = 0
        while cnt != t:
            cnt += 1
            cur = a[cur]
    else:
        t -= st
        t %= period
        cur = start
        cnt = 0
        while cnt != t:
            cnt += 1
            cur = a[cur]

    print(cur)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
import math  
import bisect  
import queue  


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


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

    res = K
    step = [-1 for _ in range(N)]
    que = queue.Queue()
    que.put(0)
    step[0] = 0
    while not que.empty():
        nc = que.get()
        nn = A[nc]
        nn -= 1
        res -= 1
        if step[nn] == -1:
            step[nn] = step[nc] + 1
            if res == 0:
                return print(nn + 1)
            que.put(nn)
        else:
            start = nn
            closer = [nn]
            while True:
                nn = A[nn] - 1
                if nn != start:
                    closer.append(nn)
                else:
                    break
            ans = res % len(closer)
            print(closer[ans] + 1)


if __name__ == '__main__':
    main()

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

n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]

visited = set()
visited.add(0)
now = 0
route = [0]

for i in range(1, n + 5):
    now = a[now] - 1
    if now in visited:
        break
    route.append(now)
    visited.add(now)

start = route.index(now)
loop = i - start

if k <= start:
    print(route[k] + 1)
else:
    k -= start
    k %= loop
    route = route[start:]
    print(route[k] + 1)

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

machi=[-1]*(N+1)
counter=0
basyo=1
while counter<K:
  counter+=1
  basyo=A[basyo]
  if machi[basyo]==-1:
    machi[basyo]=counter
  else:
    tmp=counter-machi[basyo]
    counter+=((K-counter)//tmp)*tmp
    
print(basyo)

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

def main():
    N,M = map(int,input().split())
    a = list(map(int,input().split()))
    go = [False]*N
    
    roop = [1]
    now = 1
    while True:
        go[now-1] = True
        now = a[now-1]
        if go[now-1]:
            break
        else:
            roop.append(now)
            go[now-1] = True

    ind = roop.index(now)
    r = len(roop)-ind
    if M < ind:
        print(roop[M])
    else:
        M -= ind
        M %= r
        M += ind
        print(roop[M])
    
if __name__ == "__main__":
    main()

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
b,c,d=[],set([]),0
for i in range(200000):
    b.append(d)
    c.add(d)
    if len(b)!=len(c):
        break
    d=a[d]-1
for i in range(len(b)):
    if b[-1]==b[i]:
        e=i
        break
if k<e:
    print(b[k]+1)
else:
    print(b[(k-e)%(len(b)-e-1)+e]+1)