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
def input():
    return sys.stdin.readline()[:-1]


def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    graph = []
    for i in range(N):
        graph.append(int(A[i] - 1))

    
    new = [True] * N
    num = 0
    visited = []
    while True:
        new[num] = False
        visited.append(num)
        num = graph[num]
        if not new[num]: 
            visited.append(num)
            break
    v = visited.index(visited[-1])
    l = len(visited)
    kurikaeshi = l - v - 1
    if K + 1 <= l:
        print(visited[K] + 1)
    else:
        amari = (K + 1 - v) % kurikaeshi
        if amari == 0:
            amari = kurikaeshi
        print(visited[v + amari - 1] + 1)

    
if __name__ == "__main__":
    main()

Solution (Python):
n, k = map(int, input().split())
x = list(map(int, input().split()))
count = 1
machi = 0
machi_list = [0]
next_machi = x[machi] - 1
machi_dict = [0] * n
machi_dict[0] = 1
while True:
    if machi_dict[next_machi] == 1:
        break
    count += 1
    machi_dict[next_machi] = 1
    machi_list.append(next_machi)
    machi = next_machi
    next_machi = x[machi] - 1
z = 0
for i in range(0, count):
    if machi_list[i] == next_machi:
        z = i
        break
loop_machi_list = machi_list[z:]
if k < z:
    machi = machi_list[k] + 1
    print(machi)
else:
    k = k - z
    machi = loop_machi_list[k % len(loop_machi_list)] + 1
    print(machi)

Solution (Python):
nk = list(map(int,input().split()))
n = nk[0]
k = nk[1]
a = list(map(int,input().split()))
counter = k
town = 1
seen = {
    1:0
}
cycle_p = 1
while True:
    town = a[town-1]
    counter-=1
    if counter == 0:
        break
    if town not in seen:
        seen[town]=cycle_p
        cycle_p+=1
    else:
        cycle_length = cycle_p-seen[town]
        remainder = (counter) % cycle_length
        while True:
            if remainder == 0:
                break
            town = a[town-1]
            remainder-=1
        break
print(town)

Solution (Python):

import math


def main():
    N, K = map(int, input().split())
    A = [int(i) for i in input().split()]
    round = int(math.log2(K)) + 1

    dv = []
    for _ in range(round):
        l = [0] * N
        dv.append(l)
    
    for n in range(N):
        dv[0][n] = A[n] - 1
    
    for k in range(1, round):
        for n in range(N):
            dv[k][n] = dv[k - 1][dv[k - 1][n]]
    
    a = []
    for i in range(round):
        if K>>i & 1:
            a.append(i)

    now = 0
    for i in a:
        now = dv[i][now]
    print(now + 1)

    return

if __name__ == '__main__':
    main()

Solution (Python):

import math


def main():
    N, K = map(int, input().split())
    A = [int(i) for i in input().split()]

    dv = []
    for _ in range(60):
        l = [0] * N
        dv.append(l)
    
    for n in range(N):
        dv[0][n] = A[n] - 1
    
    for k in range(1, 60):
        for n in range(N):
            dv[k][n] = dv[k - 1][dv[k - 1][n]]
    
    a = []
    for i in range(60):
        if K>>i & 1:
            a.append(i)

    now = 0
    for i in a:
        now = dv[i][now]
    print(now + 1)

    return

if __name__ == '__main__':
    main()

Solution (Python):
n = input().split()
N = int(n[0])
K = int(n[1])

listb = [1]
listc = [0]*N
C = 1
A = list(map(int, input().split()))
                 
for i in range(N):
    C = A[C-1]
    if listc[C-1] == 0:
        listb.append(C)
        listc[C-1] = 1
    else:
        D = listb.index(C)
        listb.append(C)
        break

L = len(listb) -1

if K <= N:
    print(listb[K])
else:
    if L-D == 1 or L-D == 0:
        print(C)
    else:
        M = (K-D) % (L-D)
        print(listb[(D+M)%L])

Solution (Python):
_,k,*a=map(int,open(0).read().split());a=[0]+a;p=1
while k:p=~-k%2*p or a[p];a=[a[b]for b in a];k//=2
print(p)

Solution (Python):
n,k,*a=map(int,open(0).read().split());a=[0]+a;p=1
while k:p=k%2and a[p]or p;a=[a[b]for b in a];k//=2
print(p)

Solution (Python):
n, k, *a = map(int, open(0).read().split())
a = [0] + a
p = 1
while k:
    if k % 2:
        p = a[p]
    a = [a[b] for b in a]
    k //= 2
print(p)

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

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

now = 1
while K > 0:
  if K & 1:
    now = A[now]
  A = [A[A[i]] for i in range(len(A))]
  K >>= 1

print(now)

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

now_city = 1
s_l_city = 1
t = [0] 
f = [0] 
a=0
b = 0
f_l=0
for i in range(n):
    t.append(0)
    f.append(-1)

sycle = 0
for i in range(1,n+10):
    now_city = s[now_city-1]
    
    if t[now_city-1]==1:
        
         sycle=i-f[now_city-1]
         f_l=f[now_city-1]
        
        
         b = i
        
        
         break
    t[now_city-1]+=1
    f[now_city-1]=i




if k>b:
    
    for _ in range((k-f_l)%sycle):
        
        now_city = s[now_city-1]
    
    print(now_city)
else:
    
    now_city=1
    for _ in range(k):
        now_city=s[now_city-1]
    print(now_city)

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

if K<=N:
    p=0
    for i in range (K):
        p=A[p]
    print(p+1)
else:
    p=0
    t=[-1]*N 
    t[0]=0
    for i in range(1,N):
        p=A[p] 
        if t[p]!=-1: 
            break
        t[p]=i
    d=i-t[p] 
    K-=i 
    K%=d 
    
    for i in range(K):
        p=A[p]
    print(p+1)

Solution (Python):
N, K = map(int, input().split())
A = input().split()
A = [int(a) for a in A]
S = [1]
a = 1
number = 0
numbers=[-1 for _ in range(N)]
for _ in range(N + 1):
    b = A[a - 1]
    if numbers[b-1] != -1:
      c=numbers[b-1]          
    
      break
    numbers[b-1]=number
    number += 1
    S.append(b)
    a = b
T = S[c+1:number+1]
if K <= number:
  print(S[K ])
else:
  z = K - c-1
  y = z % (number - c)

  print(T[y])

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

history = {i+1: -1 for i in range(N)}
now = 1
history[now] = 0
hist = [now]
start = -1
end = -1
for i in range(K):
    now = A[now - 1]
    hist.append(now)
    if history[now] >= 0:
        start = history[now]
        end = i + 1
        break
    history[now] = i + 1

if start < 0 or end < 0:
    print(now)
else:
    index = (K - start) % (end - start)
    print(hist[start:end][index])

Solution (Python):
n, k = map(int, input().split())
a_list = list(map(int, input().split()))
visit = [1]

for i in range(n):
    visit.append(a_list[visit[-1] - 1])

for i in range(n - 1):
    if visit[-1]  == visit[n - i - 1]:
        break
s = i + 1

for i in range(n - s):
    if visit[i] == visit[i + s]:
        break

if k < i:
    print(visit[k])
else:
    print(visit[i + (k - i) % s])

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

s = [True] * n  
c = [1]  
now = 0  
while s[now]:
    s[now] = False  
    now = a[now] - 1
    c.append(now+1)

start_cycle = c.index(c[-1]) 
loop = c[start_cycle:-1]  
cycle = len(loop)

if k < start_cycle:  
    print(c[k])
else:
    k -= start_cycle
    k %= cycle
    print(loop[k])

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

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

explored = [0] * (n+1)
t = 1
cycle = 0
while True:
    if explored[t] == 2:
        k %= cycle
        if k == 0:
            k = cycle
        explored[t] += 1
    elif explored[t] == 1:
        explored[t] += 1
        cycle += 1
    elif explored[t] == 0:
        explored[t] += 1

    k -= 1
    if k == 0:
        break
    else:
        t = a[t]
    

print(a[t])

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

array=map(int,input().split())

A=list(array)
A.insert(0,0)

visit=0
root=[]
visited=1
once=0
while True:
    if visit & (0b1<<visited):
        break
    root.append(visited)
    visit|=0b1<<visited
    once+=1
    visited=A[visited]

roop=root[root.index(visited):]
if K<once:
    print(root[K])
else:
    order=K-once
    print(roop[order%len(roop)])

Solution (Python):
n,k=map(int,input().split())
l=list(map(int,input().split()))
lcount=[0]*(n+1)
lnum=[0]*(n+1)
count=1
place=1
while lcount[place]==0:    
    lnum[place]=count
    lcount[place]=1
    place=l[place-1]
    count+=1 

dif=count-lnum[place]
if k+1<lnum[place]:
    print(lnum.index(k+1))
else:
    k=(k+1-lnum[place])%dif+lnum[place]
    print(lnum.index(k))

Solution (Python):
from numba import njit
import numpy as np


def main(N, K, A):
    d = np.zeros(N, np.int32)
    d = d-1
    p = 1
    for i in range(K):
        if d[p-1] == -1:
            d[p-1] = i
            p = A[p-1]
        else:
            p = A[p-1]
            loop = i-d[p-1]+1
            nokori = (K-d[p-1]) % loop
            for _ in range(nokori):
                p = A[p-1]
            return p
    return p


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

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

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

l = [-1]*n
l[0] = 0
order = 0
now = 0

while True:
    k -= 1
    now = a[now]
    order += 1
    if k == 0:
        break
    if l[now] != -1:
        cycle = order - l[now]
        k %= cycle
    if l[now] == -1:
        l[now] = order

print(now + 1)

Solution (Python):
N, K = map(int, input().split())
A = input().split()
A = [int(a) for a in A]
S = [1]
a = 1
number = 0
numbers=[-1 for _ in range(N)]
for _ in range(N + 1):
    b = A[a - 1]
    if numbers[b-1] != -1:
      c=numbers[b-1]
      break
    numbers[b-1]=number
    number += 1
    S.append(b)
    a = b
T = S[c+1:number+1]
if K <= number:
  print(S[K ])
else:
  z = K - c-1
  y = z % (number - c)
  print(T[y])

Solution (Python):
N, K =map(int, input().split())
A = [int(a) - 1 for a in input().split()]
idx = 0
if K<=N:
    for i in range(K):
        idx = A[idx]
    print(idx + 1)
    exit() 

t = [-1] * N
t[0] = 0
for i in range(1, N):
    idx = A[idx]
    last = i
    if t[idx] != -1:
        break
    t[idx] = i

d = i - t[idx]
K = K - i
amari = K%d

for i in range(amari):
    idx = A[idx]
print(idx + 1)

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

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

p = 0
t = [-1] * N
t[0] = 0
for i in range(1, N):
    p = A[p]
    if t[p] != -1:
        break
    t[p] = i

d = i - t[p]
K -= i
K %= d

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

Solution (Python):
from collections import deque

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

    A=list(map(lambda x:int(x)-1,input().split()))
    FootPrintA=A[:]

    loop=[]

    slack_que=deque([])
    flag=0
    t=0
    start=0
    while flag==0:
        slack_que.append(t)
        t_ = FootPrintA[t]
        FootPrintA[t]=-1
        if t_==-1:
            start=slack_que.index(t)
            flag=1
            slack_que.pop()
        t = A[t]

    slack=list(slack_que)
    slack_num=start
    loop_num=len(slack)-slack_num

    
    
    
    
    
    loop=slack[start:]
    
    if (K-slack_num)<0:
        res=slack[K]+1
    else:
        tele_num=((K-slack_num)%loop_num)
        town=loop[tele_num]
        res=town+1

    print(res)

if __name__=="__main__":
    main()

Solution (Python):

import copy
import random
import bisect 
import fractions 
import math
import sys
import collections

mod = 10**9+7
sys.setrecursionlimit(mod) 

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

N, K = LI()
A = LI()

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

next_city = 0
visited = [-1 for i in range(N)]
visited[0] = 0
for n in range(N):
    next_city = A[next_city]
    if visited[next_city] != -1:
        roop_s = visited[next_city]
        roop_cnt = n + 1 - roop_s
        break
    visited[next_city] = n + 1
ans = -1

if K - roop_s >= 0:
    amari = (K - roop_s) % roop_cnt
    next_city = 0
    for k in range(amari + roop_s):
        next_city = A[next_city]
    ans = next_city

else:
    next_city = 0
    for k in range(K):
        next_city = A[next_city]
    ans = next_city

print(ans + 1)

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

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

l = [-1]*n
now = 0
order = 0

while True:
    k -= 1
    order += 1
    now = a[now]
    if k == 0:
        break
    if l[now] == -1:
        l[now] = order
    else:
        cycle = order - l[now]
        k %= cycle

print(now + 1)

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

visit_flag=[[0]*2 for i in [1]*N]
visit_count=0
first_visit=0
last_visit=0
next_town=1
visit_flag[0][0]=1
visit_flag[0][1]=0

for i in range(K):
    visit_count+=1
    next_town = TO[next_town-1]
    if visit_flag[next_town-1][0]==0:
        visit_flag[next_town-1][0]=1
        visit_flag[next_town-1][1]=visit_count
    else:
        first_visit=visit_flag[next_town-1][1]
        last_visit=visit_count
        break

roop=last_visit-first_visit
span=visit_flag[next_town-1][1]

if K<=roop:
    next_town = 1
    for i in range(K):     
        next_town = TO[next_town-1]
    ans=next_town
else:
    if roop==0:
        ans=next_town
    else:
        for i in range((K-span)%roop):
            next_town = TO[next_town-1]
        ans=next_town

print(ans)

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

rail = [-1]*n

x = a[0]
rail[0] = 0
kasanari = -1
for i in range(10**6):
    if rail[x] == -1:
        rail[x] = i+1
        x = a[x]
    else:
        y = rail[x]
        oneroop = (i+1) - y
        break
        
if y >= k:
    for i in range(n):
        if rail[i] == k:
            print(i+1)
            
else:
    kk = (k-y) % oneroop + y
    for i in range(n):
        if rail[i] == kk:
            print(i+1)

Solution (Python):
n,k = map(int,input().split())
a = list(map(int,input().split()))
ruto = [1]
kako = [0] * (n+1)
kako[1] = 1
saki = a[0]
flag = 0
for _ in range(k):
    if kako[saki] == 1:
        where = ruto.index(saki)
        ruto = ruto[where:]
        ans = (k-where)%len(ruto)
        print(ruto[ans])
        flag = 1
        break
    else:
        ruto.append(saki)
        kako[saki] = 1
        saki = a[saki-1]
if flag == 0:    
    print(ruto[-1])

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


def main():
    n, k, *a = map(int, open(0).read().split())
    a = [i - 1 for i in a]
    

    loc = [0]
    dist = {0: 0}
    for i in range(k):
        
        if a[loc[-1]] in dist:
            ans = loc[dist[a[loc[-1]]] + (k - dist[a[loc[-1]]]) % (dist[loc[-1]] - dist[a[loc[-1]]] + 1)]
            break
        loc.append(a[loc[-1]])
        dist[loc[-1]] = i + 1
    else:
        ans = loc[-1]

    ans += 1
    print(ans)
    return(ans)


if __name__ == '__main__':
    main()

Solution (Python):

import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache

readline=sys.stdin.readline
sys.setrecursionlimit(2000000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist(): 
    return list(map(int,input().split()))
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp

N,K=inputintlist()
A=inputintlist()
for a in range(N):
    A[a]-=1
D=[[-1 for b in range(N)] for a in range(70)]
for a in range(70):
    num=2**a
    if num==1:
        for b in range(N):
            D[a][b]=A[b]
    else:
        for b in range(N):
            D[a][b]=D[a-1][D[a-1][b]]
bbin=getbin(K,70)[::-1]
now=0
for a in range(70):
    if bbin[a]==1:
        now=D[a][now]
print(now+1)

Solution (Python):

import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache

readline=sys.stdin.readline
sys.setrecursionlimit(2000000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist(): 
    return list(map(int,input().split()))
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp

N,K=inputintlist()
A=inputintlist()
for a in range(N):
    A[a]-=1
D=[[-1 for b in range(N)] for a in range(70)]
for a in range(70):
    num=2**a
    if num==1:
        for b in range(N):
            D[a][b]=A[b]
    else:
        for b in range(N):
            D[a][b]=D[a-1][D[a-1][b]]
bbin=getbin(K,70)
bbin.reverse()
now=0
for a in range(70):
    if bbin[a]==1:
        now=D[a][now]
print(now+1)

Solution (Python):

import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache

readline=sys.stdin.readline
sys.setrecursionlimit(2000000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist(): 
    return list(map(int,input().split()))
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp

N,K=inputintlist()
A=inputintlist()
for a in range(N):
    A[a]-=1
now=0
if K<10**6:
    for a in range(K):now=A[now]
else:
    history=[now]
    visited=defaultdict(lambda:False)
    visited[now]=True
    for a in range(N):
        now=A[now]
        history.append(now)
        if visited[now]:break
        visited[now]=True
    heirostart=history.index(history[-1])
    heiro=history[heirostart:-1]
    llen=K-len(history[:heirostart])
    now=heiro[llen%len(heiro)]
now+=1
print(now)

Solution (Python):
N, K = map(int, input().split())
As = list(map(int, input().split()))
As = [A-1 for A in As]
Vs = [False]*N
p = 0
Rs = [p]
Vs[p] = True
for i in range(N+3):
  n = As[p]
  Rs.append(n)
  if Vs[n]:
    break
  p = n
  Vs[p] = True
p0 = Rs.index(Rs[-1])

if K <= p0:
  r = Rs[K]
else:
  r = Rs[p0+(K-p0)%(len(Rs)-p0-1)]
print(r+1)

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

def teleport(city, end, teleportmap, count=1):

    next_city = teleportmap[city]

    if count == end:
        return next_city

    else:
        return teleport(next_city, end, teleportmap, count+1)

n, k = map(int,input().split())
a = list(map(int, input().split()))
teleportmap = dict(zip(range(1, len(a)+1), a))

if k <= n:
    print(teleport(1, k, teleportmap))

else:
    countmap = [0]*n
    countmap[0] = 1

    next_city =1
    for _ in range(1, n+1):
        next_city = a[next_city-1]
        countmap[next_city -1] += 1
        if countmap[next_city -1] == 2:
            start = next_city
            break

    roop = {}
    for j in range(1, n+1):
        roop[start] = teleportmap[start]
        start = roop[start]
    
    num_r = len(roop)

    num_until_r= 0
    for m in teleportmap.keys():
        if m not in roop and countmap[m-1] != 0:
            num_until_r += 1
    
    k_r = k - num_until_r
    num_end = k_r%num_r

    if num_end == 0:
        print(next_city)
        
    else:
        print(teleport(next_city, num_end, roop))

Solution (Python):
N, K = map(int, input().split())
towns = list(map(int, input().split()))
towns.insert(0, -1)
p = 1
tmp_move, first_move, roop_move = [1], [], []
visited = [False for _ in range(N + 1)]
res = -1

while not visited[p]:
    visited[p] = True
    tmp_move.append(towns[p])
    p = towns[p]

index = tmp_move.index(p)
roop_move = tmp_move[index:-1]
first_move = tmp_move[:index]

if K < len(first_move):
    res = first_move[K]
else:
    index = (K - len(first_move)) % len(roop_move)
    res = roop_move[index]

print(res)