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,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'

    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(1,0),(-1,0),(0,1),(0,-1)];EightNb=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('EWNS',FourNb))
l_alp=string.ascii_lowercase

input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def __str__(self):
        return  str(self.edges)

    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v

    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]

class SparseTable: 
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1

        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    
    def query(self,l,r):
        if r>self.size:r=self.size
        
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][r-(1<<N)])
    
    
    def query_id(self,l,r):
        if r>self.size:r=self.size
        
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][r-(1<<N)]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][r-(1<<N)]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])

    def print(self):
        for i in self.table:
            print(*i)


show_flg=False
show_flg=True
ans=0

n,k=LI()
a=[0]+LI()



v=[-1]*n
c=1
for i in range(n):
    k-=1
    c=a[c]
    
    if k==0:
        ans=c
        print(ans)
        exit()

t=c
loop=0
for i in range(n):
    loop+=1
    k-=1
    c=a[c]
    if c==t:
        ans=c
        break
    if k==0:
        ans=c
        print(ans)
        exit()

k=k%loop

ans=c

for i in range(k):
    
    k-=1
    c=a[c]
    if k==0:
        ans=c
        print(ans)
        exit()



print(ans)

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

B = [0] * N
C = []

C.append(0)
now = 0
B[0] = 1
for i in range(N):
    now = A[now] - 1
    if B[now] == 1:
        break
    else:
        C.append(now)
        B[now] = 1

mae = 0
for i in range(len(C)):
    if C[i] == now:
        mae = i
        break

ato = len(C) - 1

if K + 1 <= mae:
    print(C[K] + 1)
else:
    print(C[mae + (K - mae) % (ato - mae + 1)] + 1)

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

used = [False] * (N + 1)
dist = []
dist.append(1)
for i in range(N):
    v = dist[-1]
    if used[v]:
        break
    used[v] = True
    dist.append(A[v - 1])

g = dist[-1]
s = dist.index(g)

if K <= s:
    print(dist[K])
else:
    k = K - s
    index = k % (len(dist) - s - 1)
    print(dist[s + index])

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
l=[-1]*N
l[0]=0
i=1
t=0
while 1:
    t=A[t]-1
    if l[t]!=-1:
        s=i-l[t]
        break
    l[t]=i
    i+=1
if K<i:
    print(l.index(K)+1)
else:
    k=K%s
    if (i//s)*s+k in l:
        print(l.index((i//s)*s+k)+1)
    else:
        print(l.index((i//s-1)*s+k)+1)

Solution (Python):

n, k = map(int, input().split())
a = list(map(lambda x: int(x) - 1, input().split()))
g = [0] * n
for s, t in enumerate(a):
    g[s] = t

d = [-1] * n
d[0] = 0
cur = 0
while True:
    if k == 0:
        print(cur + 1)
        exit()
    k -= 1
    if d[g[cur]] >= 0:
        cycle_size = d[cur] - d[g[cur]] + 1
        k %= cycle_size
        cur = g[cur]
        while k > 0:
            cur = g[cur]
            k -= 1
        print(cur + 1)
        exit()
    d[g[cur]] = d[cur] + 1
    cur = g[cur]

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

P = [-1]*N
P[0] = 0

cnt = 0
NOW = 0
while True:
    NOW = A[NOW]
    cnt += 1
    if P[NOW] == -1:
        P[NOW] = cnt
        if cnt == K:
            print(NOW+1)
            exit()
    else:
        L = cnt - P[NOW]
        for i in range(P[NOW],P[NOW]+L):
            if K % L != i % L:
                continue
            for k,v in enumerate(P):
                if v == i:
                    print(k+1)
                    exit()

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

my_dict = dict()

ptr = 0
cnt = 0

while True:
    if ptr in my_dict:
        break
    else:
        my_dict[ptr] = cnt
        cnt += 1
        ptr = a_ls[ptr] - 1

loop = cnt - my_dict[ptr]

if k > 2 * 10 ** 5:
    k = k % loop + loop * (10 ** 6 // loop)

ptr = 0

for i in range(k):
    ptr = a_ls[ptr] - 1

print(ptr + 1)

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


already_city = [-1 for i in range(N)]
already_city[0] = 0
dep_city = 1

move_count  = 0
while move_count < K:
    move_count += 1
    dep_city = A[dep_city - 1]
    if already_city[dep_city - 1] == -1:
        already_city[dep_city - 1] = move_count
    else:
        loop_count = move_count - already_city[dep_city - 1]
        remain_ = K - move_count
        div_loop_count = remain_ % loop_count
        ans_list_num = div_loop_count + already_city[dep_city - 1]
        dep_city = already_city.index(ans_list_num) + 1
        break
        
        
print(dep_city)

Solution (Python):

n,k=map(int,input().split())
A = list(map(lambda x:int(x)-1,input().split()))
v = [-1 for _ in range(n)]
v[0] = 0
x = 0
i = 0
flag = False
while True:
    i+=1
    y = A[x]
    k-=1
    if k==0:
        break
    if not flag and v[y]>=0:
        flag = True
        t = i-v[y]
        k%=t
        x=y
        if k==0:
            print(y+1)
            exit(0)
    else:
        v[y]=i
        x=y
print(y+1)

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

cnt = defaultdict(lambda :0)
num = defaultdict(lambda :0)
cnt[1] = 1
num[1] = 1
trans = 1
for i in range(k):
    temp = a[trans - 1]
    
    if cnt[temp] != 0:
        roop = - cnt[temp] + cnt[trans] + 1
        omit = (k - cnt[temp] + 1) % roop

        ans = num[cnt[temp] + omit]
        print(ans)
        exit()
    cnt[temp] = cnt[trans] + 1
    num[cnt[temp]] = temp
    trans = temp

print(trans)

Solution (Python):
import sys
N, K = [int(x) for x in input().split()]
A = [None] + [int(x) for x in input().split()]

visited = [False] * (N + 1)
by = [None] * (N + 1)

visited[1] = True
by[1] = 0 

i = 1
tel = 0
for tel in range(1, N + 2):
    i = A[i]
    if tel == K:
        print(i)
        sys.exit(0)
    if visited[i]:
        cycle = tel - by[i]
        offset = by[i]
        break
    visited[i] = True
    by[i] = tel


M = (K - offset) % cycle

for j in range(M):
    i = A[i]

print(i)

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

flag = [False]*N
from collections import deque

q = deque([])
q.append(0)
flag[0] = True
now = 0
while True:
  now = A[now]
  if flag[now]:
    break
  else:
    flag[now] = True
    q.append(now)
    
l = list(q)
if K<len(l):
  print(l[K]+1)

else:
  for i,x in enumerate(l):
    if x==now:
      l = l[i:]
      K -= i
      break
  
  print(l[K%len(l)]+1)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

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

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    n, k = LI()
    A = LI_()
    visited = set()
    path = []
    cur = 0
    while True:
        visited.add(cur)
        path.append(cur)
        cur = A[cur]
        if cur in visited:
            break
    for i, city in enumerate(path):
        if cur == city:
            loop_st = i
            break
    loop_en = len(path) - 1
    n_loop = loop_en - loop_st + 1
    
    if k > loop_st:
        k -= loop_st
        k %= n_loop
        print(path[loop_st + k] + 1)
    else:
        print(path[k] + 1)

main()

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

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


cnt = 0
path = []
visited = [False]*n
junban = [-1]*n

now = 0
while True:

    if visited[now]:
        loopstart = now
        break
    else:
        path.append(now)
        junban[now] = cnt
        visited[now]=True
        loopend = now
        cnt+=1
        now = a[now]-1

loopsize = junban[loopend] - junban[loopstart] + 1

if k < junban[loopend]:
    print(path[k]+1)
else:
    ans = path[junban[loopstart]+ (k-junban[loopstart])%loopsize]
    print(ans+1)

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

d = {1:0}
pre_a = 0
a = 1
c = 0
while K:
    K -= 1
    next_a = A[a]
    c += 1
    if next_a in d:
        idx = d[next_a]
        n = len(d)
        K %= (n - idx)
        K += 1
        break
    else:
        d[next_a] = c
        pre_a = a
        a = next_a

while K:
    pre_a = a
    a = A[a]
    K -= 1

print(a)

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

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

path = [0]
went = {0: 0}
while True:
    town = A[path[-1]]
    if town in went.keys():
        break
    else:
        went[town] = len(path)
        path.append(town)
start = went[town]
if K < len(path):
    ans = path[K]
else:
    ans = path[(K - start) % (len(path) - start) + start]
ans += 1
print(ans)
pass

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

cur_town = 1
visited = {1: 1}
before_loop = [1]
cnt = 2
while True:
    cur_town = A[cur_town - 1]
    if cur_town in visited:
        break
    visited[cur_town] = cnt
    before_loop.append(cur_town)
    cnt += 1


before_loop_cnt = visited[cur_town] - 1
if K < before_loop_cnt:
    print(before_loop[K])
else:
    loop_lst = before_loop[visited[cur_town] - 1 :]
    print(loop_lst[(K - before_loop_cnt) % len(loop_lst)])

Solution (Python):




class Node(object):

  def __init__(self, idx):
    self.idx = idx
    self.jump = None
    self.step = None


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

  for i, a in enumerate(map(int, input().split())):
    nodes[i].jump = nodes[a - 1]

  current = nodes[0]
  current.step = 0

  while current.jump.step is None:
    current.jump.step = current.step + 1
    current = current.jump

  loop = current.step - current.jump.step + 1

  if K >= current.jump.step:
    remain = (K - current.jump.step) % loop
    current = current.jump
  else:
    remain = K
    current = nodes[0]

  for _ in range(remain):
    current = current.jump

  print(current.idx + 1)


if __name__ == '__main__':
  main()

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
v=[0]*n
v[0]=1
i=1
l=[1]
while True:
  i=a[i-1]
  l.append(i)
  if v[i-1]:
    t=i
    break
  else:
    v[i-1]=1
pre=l.index(t)
loop=len(l)-pre-1
if pre>=k:
  print(l[k])
else:
  k=k-pre
  mod=k%loop
  print(l[pre+mod])

Solution (Python):


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


p = [1]
hash = {1: 0}  
while True:
    x = a[p[-1] - 1]
    if x in hash:
        break
    hash[x] = len(p)  
    p.append(x)


looplen = len(p) - hash[x]
if k < len(p):
    print(p[k])
else:
    print(p[(k - len(p)) % looplen + hash[x]])

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

kyori = [-1]*n

now = 0;kyori[now] = 0
jyunkan = 0;v = 0
for i in range(n):
    tugi = a[now] - 1
    if kyori[tugi] != -1:
        jyunkan = kyori[now] + 1
        v = tugi
        break
    kyori[tugi] = kyori[now] + 1
    if kyori[tugi] == k:
        print(tugi + 1)
        sys.exit()
    now = tugi
k -= kyori[v]
mawaru = jyunkan - kyori[v]
amari = k % mawaru

now = v;cunt = 0
for i in range(amari):
    now = a[now] - 1
    
print(now + 1)

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

visited = [-1] * len(a)

now = 0
visited[0] = 0
while k > 0:
    k -= 1
    old = now
    now = a[now]
    if visited[now] != -1:
        p = visited[old] + 1 - visited[now]
        k %= p
        visited = [-1] * len(a)
    else:
        visited[now] = visited[old] + 1
print(now + 1)

Solution (Python):
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())


    
n,m=mi()
a=li()
x=[]
c=1
k=0
m1={}
m1[1]=k
k+=1
x1=0
while(1):
    if a[c-1] in m1:
        x1=a[c-1]
        break
    m1[a[c-1]]=k
    k+=1
    c=a[c-1]
if(m<k):
    for i in m1.keys():
        if m1[i]==m:
            print(i)
            break
else:
    m-=k
    m1={}
    m1[x1]=0
    k=1
    c=a[c-1]
    while(1):
        if a[c-1] in m1:
            break
        m1[a[c-1]]=k
        k+=1
        c=a[c-1]
    m%=k
    for i in m1.keys():
        if m1[i]==m:
            print(i)
            break

Solution (Python):
n,k,*a=map(int,open(0).read().split())
a=[x-1 for x in a]
dist=[0]*n
cur=0
while True:
	nxt=a[cur]
	if k==0:
		print(cur+1)
		break
	if dist[nxt]:
		k=(k-dist[nxt])%(dist[cur]-dist[nxt]+1)+dist[nxt]
		k-=1
		dist=[0]*n
		cur=nxt
	else:
		k-=1
		dist[nxt]=dist[cur]+1
		cur=nxt

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

x = 0
l = [0]
s = set([0])
flag = False
for i in range(N):
    x = A[x]-1
    if x in s:
        break
    s.add(x)
    l.append(x)

for i in range(len(l)):
    if l[i]==x:
        break

y = len(l)
z = i

if K<len(l):
    print(l[K]+1)
else:
    
    
    
    
    
    print(l[z + (K-z)%(y-z)]+1)

Solution (Python):
nk = input().split()
n = int(nk[0])
k = int(nk[1])

a = list(map(lambda x:int(x), input().split()))

visited_i = [-1]*n

i = 0
visited_i[0] = 0

loops = -1
loopn = -1

nowp = 0
while i < k:
  i += 1
  nowp = a[nowp]-1
  
  
  if visited_i[nowp] != -1 and loops == -1:
    loops = nowp
    loopn = i-visited_i[nowp]
    
    
    
    
    k = (k-i)% loopn
    i = 0
    
  else:
  	visited_i[nowp] = i


print(nowp+1)

Solution (Python):



def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    

    
    

    n,k = map(int, input().split())
    a = list(map(int, input().split()))
    tugi = [0]*n
    tugi[0] = 1
    s = 0
    cnt = 1
    while 1:
        s = a[s] - 1
        cnt += 1
        if tugi[s] > 0:
            break
        tugi[s] = cnt
    cnt -= 1
    if cnt-1 >= k:
        for i in range(n):
            if tugi[i]==k+1:
                print(i+1)
    else:
        
        loop = [s]
        for i in range(cnt - (tugi[s]-1)-1):
            s = a[s] - 1
            loop.append(s)
        s = a[s]-1
        amari = (k-(tugi[s]-1)) % (len(loop))
        print(loop[amari]+1)

if __name__ == '__main__':
    main()

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

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

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

seen[0] = 0

cur = 1

fin = 0

for step in range(1, n+3):
    n_c = a[cur-1]
    if step == k:
        fin = 1
        print(n_c)
        break
    if seen[n_c-1] >= 0:
        loop = step - seen[n_c-1]
        before = seen[n_c-1]
        start = n_c
        break
    seen[n_c-1] = step
    cur = n_c

if not fin:
    if loop == 0:
        print(start)
    else:
        rem = k - before
        ama = rem % loop
        cur = start
        for i in range(ama):
            n_c = a[cur-1]
            cur = n_c
        print(cur)

Solution (Python):
N, K = map(int, input().split())
*A, = map(int, input().split())
s = 0
l = 0
n = 0
h = [0]*N
while True:
    h[s] = l
    s = A[s]-1
    l += 1
    if h[s]:
        n = l-h[s]
        break

if K < h[s]:
    s = 0
else:
    K -= h[s]
    K = K % n

while K > 0:
    s = A[s]-1
    K = K-1
print(s+1)

Solution (Python):
if __name__ == '__main__':
    from sys import stdin
    
    
    
    import numpy as np
    
    
    input = stdin.readline


    n, k = map(int, input().split())
    aa = [0]+list(map(int, input().split()))
    arrive = [1]
    next = aa[1]
    visited = set([1])
    if next == 1:
        print(1)
        exit()
    while not (next in visited):
        arrive.append(next)
        visited.add(next)
        next = aa[next]
    num_town = len(arrive)
    start_index = arrive.index(next)
    if k < num_town:
        print(arrive[k])
        exit()
    print(arrive[start_index+(k-start_index)%(num_town-start_index)])

Solution (Python):
n,k = map(int, input().split())
a = list(map(int, input().split()))
now = 1
used = [0]*n
for i in range(1,2*n):
    now = a[now-1]
    if (used[now-1]==0):
        used[now-1]=i
    else:
        bef = used[now-1]
        loop = i-used[now-1]
        break
if (bef>=k):
    print(used.index(k)+1)
else:
    over = (k-bef)%loop
    
    print(used.index(bef+over)+1)

Solution (Python):
def main():
    N, K = [int(_n) for _n in input().split()]
    A = [int(_n)-1 for _n in input().split()]
    visited = [-1] * N
    loop = []
    current = 0
    siz = 0
    visited[0] = 0
    loop.append(0)
    start = 0
    while True:
        current = A[current]
        siz += 1
        if visited[current] != -1:
            start = visited[current]
            break
        visited[current] = siz
        
        loop.append(current)
    
    
    if K <= start:
        print(loop[K]+1)
    else:
        print(loop[start + (K-start)%(len(loop)-start)]+1)

    
main()

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
visited = {1: 0}
log = {0: 1}
current = 1
move = 0
roop_exist = False
while True:
    move += 1
    current = A[current - 1]
    if current in visited:
        roop = move - visited[current]
        roop_start = current
        roop_exist = True
        break
    if move == K:
        print(current)
        break
    visited[current] = move
    log[move] = current
if roop_exist:
    remain = (K - move) % roop
    print(log[visited[roop_start] + remain])

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

now = 0
cnt[now] += 1
root_to_loop = [now]
while cnt[now] != 2:
    now = a[now] - 1
    root_to_loop.append(now)
    cnt[now] += 1

loop = [now]
while cnt[now] != 3:
    now = a[now] - 1
    loop.append(now)
    cnt[now] += 1

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

Solution (Python):
N, K = map(int, input().split())
*A, = map(int, input().split())
visited = [False] * N
towns = []
now = 0
length = 0
while not visited[now] and K > 0:
    visited[now] = True
    towns.append(now + 1)
    length += 1
    K -= 1
    now = A[now] - 1
if K == 0: print(now + 1)
else:
    idx = towns.index(now + 1)
    length -= idx
    print(towns[idx:][K % length])

Solution (Python):


import sys

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

Flag = [0] * (N+1)
X = [0] * (N + 1)
X[0] = 1

for i in range(1, K + 1):
    if Flag[A[X[i - 1] - 1]] == 1:
        
        hoge = X.index(A[X[i - 1] - 1])
        print(X[hoge + ((K - hoge) % ((i-1) - hoge + 1))])
        sys.exit()
    else:
        X[i] = A[X[i - 1] - 1]
        Flag[A[X[i - 1] - 1]] = 1


print(X[K])

Solution (Python):
inf=10**15
n,k=map(int,input().split())
a=list(map(int,input().split()))
num=[inf]*n
num[0]=0
now=0
for i in range(n):
	now=a[now]-1
	if num[now]==inf:
		num[now]=i+1
	else:
		loop=i+1-num[now]
e=-1
for i in range(n):
	if num[i]!=inf:
		if e<num[i]:
			e=num[i]
if e>=k:
	for i in range(n):
		if num[i]==k:
			print(i+1)
			break
else:
	k-=e
	k%=loop
	for i in range(n):
		if num[i]==e:
			now=i
			break
	for i in range(k):
		now=a[now]-1
	print(now+1)

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

A = [a-1 for a in A]

g = [[] for i in range(n)]
for i, a in enumerate(A):
    g[i].append(a)

s = []
visit = [-1]*n
s.append(0)
visit[0] = 0
while s:
    v = s.pop()
    for u in g[v]:
        if visit[u] == -1:
            visit[u] = visit[v]+1
            s.append(u)
        else:
            temp = visit[u]


d = max(visit)-temp+1

if k < temp:
    for i in range(n):
        if visit[i] == k:
            print(i+1)
            exit()
else:
    q, r = divmod(k-temp, d)
    for i in range(n):
        if visit[i]-temp == r:
            print(i+1)
            exit()

Solution (Python):

N, K = map(int, input().split())
A = [int(c) -1 for c in input().split()]

is_used = [False for _ in range(N)]
cycle_head, cycle_tail = -1, -1
cur, k = 0, 0
while True:
    if k == K:
        print(cur+1)
        exit()

    next_cur = A[cur]
    if is_used[next_cur]:
        head = next_cur
        tail = cur
        break

    else:
        is_used[cur] = True
        cur = next_cur
        k += 1


before_cycle = 0
len_cycle = 1
cur = 0
while cur != head:
    before_cycle += 1
    cur = A[cur]

while cur != tail:
    len_cycle += 1
    cur = A[cur]


k = (K - before_cycle) % len_cycle
cur = head
while k != 0:
    k -= 1
    cur = A[cur]
print(cur+1)

Solution (Python):
import collections

n,k=map(int,input().split())
a=list(map(int,input().split()))
L=[1]
count=1
nowt=1
roops=0
v=[False]*n
while(True):
    if v[a[nowt-1]-1]==True:
        roops=a[nowt-1]
        break

    L.append(a[nowt-1])
    v[a[nowt-1]-1]=True
    nowt=a[nowt-1]
    count+=1

play=0
for i in range(len(L)):
    if L[i]==roops:
        break
    play+=1

rooplen=len(L)-play

if k<play:
    print(L[k])
    exit() 

ans=L[play+(k-play)%rooplen]

print(ans)

Solution (Python):

import sys

stdin = sys.stdin
ns = lambda: stdin.readline().rstrip() 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))


def main():
    n,k = na()
    As = [a-1 for a in na()]
    memo = [[0]] + [[] for _ in range(n-1)]
    now = 0
    time = 0
    while k > 0:
        time += 1
        now = As[now]
        k -= 1
        if len(memo[now]) < 2:
            memo[now] += [time]
        if len(memo[now]) == 2:
            shortcut = memo[now][1] - memo[now][0]
            k %= shortcut
    print(now+1)
    return


if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
flag = [0] * (N+1)
cnt = [0] * (N+1)
now = 0
i = 1
while(flag[i] == 0 and K > now):
  flag[i] = 1
  cnt[i] = now
  i = A[i-1]
  now += 1
if(K <= now):
  print(i)
else:
  loop = now-cnt[i]
  kn = (K-now)%loop
  for j in range(kn):
    i = A[i-1]
  print(i)

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

t = [[] for _ in range(n)]
u = 0
for i in range(k + 1):
    t[u].append(i)
    if len(t[a[u] - 1]) == 2:
        break
    else:
       u = a[u] - 1
ans = 0
for i in range(n):
    if len(t[i]) == 2 and (k - t[i][1]) % (t[i][1] - t[i][0]) == 0:
        ans = i + 1
        break
    elif len(t[i]) == 1 and t[i][0] == k:
        ans = i + 1
        break
print(ans)

Solution (Python):
from sys import stdin


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    N, K = list(map(int,_in[0].split(' ')))  
    A_arr = [0]+list(map(int,_in[1].split(' ')))  
    
    period = N
    visit = [False] * (N+1)
    order = []
    next_visit = 1
    for i in range(N):
        order.append(next_visit)
        visit[next_visit] = True
        next_visit = A_arr[next_visit]
        if visit[next_visit]:
            period = len(order[order.index(next_visit):])
            ofst = len(order[:order.index(next_visit)])
            break
    if K<=ofst:
        cnt = order[K]
    else:
        tmp = order[order.index(next_visit):]
        cnt = tmp[(K-ofst)%period]
    
    print(cnt)

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

now=0
cnt=0
from collections import defaultdict
d = defaultdict(lambda: -1)

d[0]=0

while True:
    cnt+=1
    nxt=a[now]-1
    now=nxt
    if k==cnt:
        print(nxt+1)
        exit()
    if d[nxt]!=-1:
        break
    d[nxt]=cnt

k-=d[nxt]
k%=(cnt-d[nxt])

cnt=0
while cnt<k:
    cnt+=1
    nxt=a[now]-1
    now=nxt

print(now+1)

Solution (Python):


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

    
    if k < n:
        curr = 1
        while k:
            curr = a[curr]
            k -= 1
        print(curr)
        return
            
    
    attach = {i: -1 for i in range(1, n + 1)}
    curr = 1
    cnt = 0
    while True:
        if attach[curr] < 0:
            attach[curr] = cnt
            curr = a[curr]
            cnt += 1
        else:
            break
    
    loop_st = curr
    loop_time = cnt - attach[curr]
    
    skip = ((k - attach[loop_st]) // loop_time) * loop_time
    k -= skip

    curr = 1
    while k:
        curr = a[curr]
        k -= 1
    print(curr)
    return
    

submit()

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

route = [0]
visited = [0]*n
visited[0]=1

while visited[a[route[-1]]-1]==0:
    visited[a[route[-1]]-1]=1
    route.append(a[route[-1]]-1)

if k<len(route):
    print(route[k]+1)
else:
    b = route.index(a[route[-1]]-1)
    ans = (k-b)%(len(route)-b)
    print(route[b+ans]+1)