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

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

route = [1]
appearance = set()
index = 1
cnt = 0
flg = False
for _ in range(k):
    if index in appearance:
        flg = True
        break
    appearance.add(index)
    cnt += 1
    next_city = A[index - 1]
    route.append(next_city)
    index = next_city

if flg is False:
    print(route[k])
    sys.exit()


duplicate = route[route.index(index):len(route) - 1]
print(duplicate[(k - cnt) % (len(duplicate))])

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

A_list = [int(a) for a in input().split()]




keiro = [1]
visit_town = [0]*N

town = 1
c = 1
while True:
    visit_town[town - 1] = c
    c += 1
    town = A_list[town - 1]
    

    if len(keiro) > 1 and visit_town[town-1] != 0:
        break
    keiro.append(town)






first_visit = keiro[:visit_town[A_list[keiro[-1]-1]-1]-1]
loop_visit = keiro[visit_town[A_list[keiro[-1]-1]-1]-1:]




if K <= len(first_visit)-1:
    print(first_visit[K])
else:
    l = K - len(first_visit)
    
    c = (l) % len(loop_visit)
    
    print(loop_visit[c])

Solution (Python):
n, k = map(int, input().split())
data = list(map(int, input().split()))
visited = [False for _ in range(n)]
nex = 0
visited[0] = True
while True:
    nex = data[nex]-1
    if visited[nex] is True:
        break
    else:
        visited[nex] = True
start = nex
cycle = 1
c = [start]
while True:
    nex = data[nex]-1
    if nex == start:
        break
    else:
        cycle += 1
        c.append(nex)
nex = 0
before = 1
while True:
    nex = data[nex]-1
    if nex == start:
        break
    else:
        before += 1

if k < before:
    nex = 0
    n = 0
    while n < k:
        nex = data[nex]-1
        n += 1
    print(nex+1)
elif start != 0:
    print(c[(k-before)%cycle]+1)
else:
    print(c[k%cycle]+1)

Solution (Python):


import copy

N, K = map(int, input().split())
List = list(map(int, input().split()))
saki=[1]
ato=[]

i=0
j=1
while i<N:
    saki.append(List[j-1])
    j=List[j-1]
    i+=1

ato.append(List[j-1])

if K<=N:
    print(saki[K])
    quit()

start=saki.index(ato[0])

SA=(len(List)-start)+1

o=0
check=[]
while o<SA:
    check.append(List[j-1])
    j=List[j-1]
    o+=1
print(check[(K-start)%SA])

Solution (Python):
def main():
    N,K=map(int,input().split())
    A=list(map(int,input().split()))
    pos=set()
    pos.add(0)
    i=0
    traversal=[0]
    start=0
    nodes=[1]
    while(start<K):
        position=A[i]-1
        if position in pos:
            break
        traversal.append(position)
        pos.add(position)
        start+=1
        nodes.append(A[i])
        i=position
    if start==K:
        print(nodes[-1])
    else:
        ind=traversal.index(position)
        interval=len(traversal)-ind
        print(nodes[ind+((K-ind)%interval)])
if __name__=='__main__':
    main()

Solution (Python):
















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


if K<=N:
    i = K
    j = 1
    while i > 0:
        j = lisA[j]
        i -= 1
    print(j)
    exit()

checked = {1:0}
roopstnum = 0
i = 1
for n in range(1,N+2):
    if not lisA[i] in checked:
        checked[lisA[i]] = n
        i = lisA[i]
    else:
        roopstnum = lisA[i]
        roopstidx = checked[roopstnum]
        rooplen = n - roopstidx
        break


warukazu = rooplen
for k,v in checked.items():
    if (K-roopstidx) % warukazu == v - roopstidx:
        ans = k
print(ans)

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

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

    
    
    
    
    

    visited = [0]
    visited_set = set([0])
    now = 0
    ind = 0
    my_append = visited.append
    my_add = visited_set.add
    for i in range(K):
        a = A[now]-1
        if a in visited_set:
            ind = visited.index(a)
            break
        else:
            my_add(a)
            my_append(a)
            now = a
            

    loop_visited = visited[ind:]
    ans_ind = (K-ind) % len(loop_visited)

    print(loop_visited[ans_ind]+1)


if __name__ == "__main__":
    main()

Solution (Python):
N ,K = map(int, input().split())
A = list(map(int, input().split()))
B = [0]
C = {} 
C[0] = 0
cnt = 0
jdg = 0
q = 0
while jdg == 0:
    i = A[q]-1
    q = i
    if q in C:
        l = C[q]
        
        break
    cnt += 1
    B.append(i)
    C[i] = cnt
r = cnt+1





H = B[l:r]

M = (K-l)%(r-l)

if K >= r:
	print(H[M]+1)
else:
  print(B[K]+1)

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

root = list()


def dfs(A, num, N, memo):
    if memo[A[num]-1] == 1:
        return root.index(A[num])
    else:
        root.append(A[num])
        memo[A[num]-1] = 1
        return dfs(A, A[num]-1, N, memo)


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

    memo = [0] * N
    start = dfs(A, 0, N, memo)

    if K <= len(root):
        print(root[K-1])
    else:
        index = (K - start) % (len(root)-start)
        loop = root[start:]
        print(loop[index-1])


if __name__ == "__main__":
    main()

Solution (Python):
(town, tele)=[int(x) for x in input().split()]
pos=[int(x) for x in input().split()]
move=[pos[0]]
move_dict={i:0 for i in range(1, town+1)}
while move_dict[move[-1]] <= 1 and len(move) < tele:
  move.append(pos[move[-1]-1])
  move_dict[move[-1]]+=1
if len(move) < tele:
  loop_move=move[move.index(move[-1]):-1]
  print(loop_move[(tele-(len(move)-1))%len(loop_move)-1])
else:
  print(move[-1])

Solution (Python):

def getlooptime(warpmap, start='1'):
    warpmap_ = warpmap.copy()    
    counter = 0

    for _ in range(N):

        counter += 1

        nextmap = warpmap_[start]

        if type(nextmap) == int:
            return counter - 1, (counter - 1) - (nextmap - 1)
        
        warpmap_[start] = counter
        start = nextmap

def getterminal(warpmap, n, start):
    warpmap_ = warpmap.copy()

    if n == 0:
        return start
    else:
        for _ in range(1, n + 1):
            nextmap = warpmap_[start]
            start = nextmap

        return nextmap


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

warpmap = {}

for town_num, to_warp in enumerate(A):
    
    town_num = town_num + 1
    warpmap[f"{town_num}"] = f"{to_warp}"

pasttime, looptime = getlooptime(warpmap=warpmap, start='1')

if K > pasttime:
    print(getterminal(warpmap=warpmap, n=(K - pasttime) % looptime, start=getterminal(warpmap=warpmap, n=pasttime, start='1')))
else:
    print(getterminal(warpmap=warpmap, n=K, start='1'))

Solution (Python):
import sys
from math import factorial
from collections import Counter
from fractions import Fraction
import heapq, bisect, fractions
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
MOD = 10**9 + 7

n, k = MAP()
a = LIST()
tugi = [0]+a
town  =1
route = [0]*n
route[0] = town
used = [False]*n
used[0] = True
for i in range(n):
    town = tugi[town]
    if used[town-1]:
        i = route.index(town)
        notcycle = route[:i]
        cycle = route[i:]
        break
    used[town-1] = True
    route[i+1] = town

for i in range(n):
    if cycle[i] == 0:
        cycle = cycle[:i]
        break

if len(notcycle) >k:
    print(notcycle[k])
else:
    k -= len(notcycle)
    print(cycle[k%len(cycle)])

Solution (Python):

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

P=[1]
S=[0]*N
S[0]=1
now=1

for i in range(K):
    now=A[now-1]
    if S[now-1]==1:
        x = i+1
        y = P.index(now)
        break
    elif i == K-1:
        print(now)
        exit()
    else:
        P.append(now)
        S[now-1]=1

c=(K-y)%(x-y)

print(P[y+c])

Solution (Python):
N,K=map(int,input().split())
A=list(map(lambda x:int(x)-1,input().split()))
seen=[-1]*N
i=0
cnt=0
iri=-1

while True:
    if(cnt==K):
        print(i+1)
        exit()
    if seen[i]!=-1:
        roop=cnt-seen[i]
        iri=i
        K-=seen[i]
        K=K%roop
        break
    seen[i]=cnt
    cnt+=1
    i=A[i]
now=iri
for i in range(K):
    now=A[now]


print(now+1)

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

visited = [0] * n
next_town = 0
order = []

while True:
    if visited[next_town]:
        break
    order.append(next_town)
    visited[next_town] = 1
    next_town = a[next_town]

first_loop = len(order)
offset = order.index(next_town)
second_loop = first_loop - offset

if k < first_loop:
    print(order[k] + 1)
else:
    print(order[offset + (k - first_loop) % second_loop] + 1)

Solution (Python):


import sys
input= lambda: sys.stdin.readline().rstrip()
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))

def resolve():
    N,K=pin()
    A=list(pin())
    seen=set([0])
    junban=[0]
    
    
    
    point_1=0
    for n in range(N):
        
        point_1=A[point_1]-1
        junban.append(point_1)
        if (point_1) in seen:
            
            b=n
            break 
        seen.add(point_1)
        
        
    
    for m in range(len(junban)):
        if junban[m]==point_1:
            a=m
            break
    g=(len(junban)-1-a)
    
    if K>a:
        k=(K-a)%g
        print(junban[a+k]+1)
    else:print(junban[K]+1)

resolve()

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

h = set([])

c = 0
for i in range(2 * n):
  c = a[c] - 1
  if n < i:
    if c + 1 in h:
      break
    else:
      h.add(c + 1)

c = 0
d = 0
for i in range(n):
  c = a[c] - 1
  if c + 1 in h:
    break
  else:
    d += 1

c = 0
if d >= k:
  for i in range(k):
    c = a[c] - 1
else:
  for i in range(d + ((k - d) % len(h) + len(h))):
    c = a[c] - 1


print(c + 1)

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

lst = [0] * N
k = 1
cnt = 0
for j in range(10*N):
  lst[k-1] += 1
  k = A[k-1]
num = len(list(filter(lambda x:x>=1,lst)))
k = 1
first = []
loop = []
for j in range(num):
  if lst[k-1] == 1:
    first.append(k)
  elif lst[k-1] > 1:
    loop.append(k)
  k = A[k-1]
if K < len(first):
  print(first[K])
else:
  K -= len(first)
  print(loop[K%len(loop)])

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

Solution (Python):
nums = [int(e) for e in input().split()]
n = nums[0]
k = nums[1]
a = [int(e) for e in input().split()]

town = 1
count = 0
visit = [0] * n

i = 0
while i < k:
    count += 1
    i = i+1
    next_town = a[town-1]
    if visit[town-1] > 1:
        k = (k-i)%(count-1)
        i = 0
    elif visit[town-1] == 0:
        count = 0
    visit[town-1] += 1
    town = next_town

print(town)

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
now = 1
cnt = 0
loop = 0
cnts = [-1] * n
cnts[now - 1] = cnt
visited = [False] * n
visited[now - 1] = True
li = [now]

while True:
    cnt += 1
    now = a[now - 1]
    li.append(now)

    if cnt == k:
        print(now)
        exit()
    if visited[now - 1]:
        loop = (cnt - cnts[now - 1])
        pre = cnts[now - 1]
        print(li[pre + (k - pre) % loop])
        exit()

    cnts[now - 1] = cnt
    visited[now - 1] = True

Solution (Python):

import sys
def p(*_a):
  _s=" ".join(map(str,_a))
  
  sys.stderr.write(_s+"\n")

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


M = [ [0,0] for _ in range(N+1) ]			

p(M)

i = 1
x = y = 0
for k in range(K):
	x,y = M[i]
	
	if x==0:
		M[i][0] = A[i]
		M[i][1] = k
		i = A[i]
		continue
	
	
	a = K - y
	b = a % (k-y)
	for _ in range(b):
		i = A[i]
	
	p(x,y,k)
	p("M[1:]", M[1:])
	
	break

ans = i
print(ans)

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

vislist=[1]
visset={1}
loopflag=True
endflag=False
donek=0
ima=1

while loopflag:
    ima=alist[ima-1]
    if ima in visset:
        loopflag=False
        if ima == alist[ima-1]:
            endflag=True
    else:
        vislist.append(ima)
        visset.add(ima)

        donek+=1

        if donek == k:
            loopflag=False
            endflag=True

if endflag:
    print(ima)
    sys.exit()

loopstartindex=vislist.index(ima)
looplength=len(visset)-loopstartindex
if (k+1-loopstartindex)%looplength == 0:
    print(vislist[-1])
else:
    print(vislist[loopstartindex+(k+1-loopstartindex)%looplength-1])

Solution (Python):
DEBUG = False

import time

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

visited = [False] * N
next = A[0]
visited[0] = True
K -= 1
while not visited[next]:
    if DEBUG:
        print("K: {}, next: {}".format(K, next))
        print("visited: {}".format(visited))
        time.sleep(0.1)
    if K == 0:
        print(next+1)
        exit()
    visited[next] = True
    next = A[next]
    K -= 1

K -= 1
now = next
count = 1
next = A[next]
while now != next:
    next = A[next]
    count += 1
if DEBUG:
    print("count: {}".format(count))

K %= count

if DEBUG:
    print("now: {}, count: {}, K: {}".format(now, count, K))

while K > 0:
    if DEBUG:
        print("now: {}".format(now))
    now = A[now]
    K -= 1

print(A[now]+1)

Solution (Python):
N,K = list(map(int, input().split()))
A = list(map(int, input().split()))
 
B = [1]
go = [0]*N
hop = 0
ans = 0
for n in range(N):
    nc = A[B[n]-1]
    if go[nc-1] == 1:
        idx = B.index(nc)
        loop = B[idx:]
        break
    B.append(nc)
    K -= 1
    go[nc-1] = 1
    ans = nc
    if K < 1:
        break
 
if K > 0:
    L = len(loop)
    K = K % L
    K -= 1
    ans = loop[K]
print(ans)

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

c = 0
count= 0
now=1
flag = 0

while(c < K):
  now = A[now-1]
  c += 1
  if(C[now-1] == 1):
    for i in range(len(B)):
      if(now == B[i]):
        flag = 1
        count = i
        break
  if(flag == 1):
    break
  B.append(now)
  C[now-1] = 1
if(c == K):
  print(now)
else:
  print(B[(K-count)%(len(B)-count)+count])

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

x = [-1] * n
y = -1

while cnt < k:
    if x[ans] == -1:
        x[ans] = cnt
        ans = a[ans]
        cnt += 1
    else:
        y = x[ans] + (k-cnt) % (cnt-x[ans])
        break

if y == -1:
    print(ans+1)
else:
    print(x.index(y) +1)

Solution (Python):
n,k = map(int, input().split())
a = list(map(int, input().split()))
row = []
been = [0]*n
now = 0
nex = 0
t = 0
l = [-1]*n
prev = 0
while been[now] == 0:
    l[now] = t
    row.append(now)
    been[now] = 1
    now = a[now]-1
    t += 1
    if been[now] == 1:
        prev = l[now]

print(row[prev + (k-prev)%(t-prev)]+1 if k > prev else row[k]+1)

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

dist = {}
for idx, d in enumerate(A):
  dist[idx+1] = d

n = 1
hist = [1]
already = {1}
flag = True
for i in range(K):
  n = dist[n]
  if n in already:
    flag = False
    break
  already.add(n)
  hist.append(n)
if flag:
  print(n)
else:
  start = hist.index(n)
  loop = hist[start:]
  print(loop[(K - start) % len(loop)])

Solution (Python):
N, K = map(int, input().split())
dst = list(map(int, input().split()))
log = [1]
log_set=set(log)
current = 1
for i in range(1, K+1):
    current = dst[current-1]
    if current in log_set:
        loop_start_ind = log.index(current)
        loop_len = i-loop_start_ind
        current = log[loop_start_ind+(K-i) % loop_len]
        break
    else:
        log.append(current)
        log_set.add(current)
print(current)

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

for i in range(n):
    a[i] -= 1
    
log_size = times.bit_length() + 2
double = [[-1] * n for i in range(log_size)]


for i in range(n):
    double[0][i] = a[i]


for k in range(1, log_size):
    for i in range(n):
        double[k][i] = double[k - 1][double[k - 1][i]]

ans = 0
for i in range(70)[::-1]:
    if times & (1 << i):
        ans = double[i][ans]
print(ans + 1)

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

flag=0
def woap(current_city,li,K):
    global flag
    next_city=li[current_city]-1
    if trace[next_city]!=-1 and trace[next_city]!=K:
        flag=1
        return current_city
    else:
        trace[next_city]=K
        return next_city

def woap2(current_city,li):
    next_city=li[current_city]-1
    return next_city

trace=[-1]*N
trace[0]=0
rest=K
current_city=0
for i in range(1,K+1):
    current_city=woap(current_city,A,i)
    if flag==1:
        break
    else:
        rest-=1


loop_length=K-rest-trace[A[current_city]-1]+1
amari=rest%loop_length
for i in range(amari):
    current_city=woap2(current_city,A)

print(current_city+1)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
r = [None] * N
i = 0
cur = 0
m = None
while True:
    if m is None and r[cur] is not None:
        m = i - r[cur]
        K = i + (K-i)%m
    else:
        r[cur] = i
    if i == K:
        print(cur+1)
        exit()
    i += 1
    cur = A[cur] - 1

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

root = [1]
pastTown = {1:0}
t = 0
nextTown = 1

while 1:
  t += 1
  nextTown = int(A[nextTown - 1])
  if nextTown in pastTown.keys():
    break
  else:
    root.append(nextTown)
    pastTown[nextTown] = t

if nextTown == root[0]:
  town = root[K % len(root)]
else:
  if K <= pastTown[nextTown]:
    town = root[K]
  else:
    tmp = (K - pastTown[nextTown]) % (len(root) - pastTown[nextTown])
    town = root[pastTown[nextTown] + tmp]

print(town)

Solution (Python):
n,k = map(int,input().split())
l = list(map(int,input().split()))
s = set()
s.add(1)
pas1 = [1]
pas2 = []
now = 1
count = 0
if k == 1:
    print(l[0])
    exit()
for i in range(2*n):
    a = l[now-1]
    if a in s:
        index = pas1.index(a)
        k -= index
        le = len(pas1)-index
        print(pas1[k%le+index])
        
        exit()
    else:
        now = a
        s.add(a)
        count += 1
        pas1.append(a)
        
        if count == k:
            print(a)
            exit()

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

visited = [-1 for i in range(n)]
visited_history = []
machi = 0
before = -1
loop = -1
flag = False
for idx in range(k):
    machi = a[machi] - 1
    if visited[machi] == -1:
        visited[machi] = idx
        visited_history.append(machi)
    else:
        before = visited[machi]
        loop = idx - before
        flag = True
        break

if flag:
    k -= before
    idx = k % loop - 1
    if idx == -1:
        idx = loop - 1
    machi = visited_history[idx + before]

ans = machi + 1
print(ans)

Solution (Python):
import sys
from collections import defaultdict, Counter, deque
from itertools import accumulate, permutations, combinations
from operator import itemgetter
from bisect import bisect_left, bisect_right, bisect
from heapq import heappop, heappush
from fractions import gcd
from math import ceil, floor, sqrt, cos, sin, pi
from copy import deepcopy




N = None
K = None
A = None

def check(start):
    global N,K,A
    slow = A[start]
    fast = A[A[start]]
    while slow != fast:
        slow = A[slow]
        fast = A[A[fast]]

    slow = start
    while slow != fast:
        slow = A[slow]
        fast = A[fast]

    cycle_start = slow

    cycle_length = 1
    slow = A[slow]
    fast = A[A[fast]]
    while slow != fast:
        slow = A[slow]
        fast = A[A[fast]]
        cycle_length += 1

    return cycle_start, cycle_length

def main():
    global N,K,A
    N,K = map(int, input().split())
    A = list(map(int, input().split()))
    A = [""] + A
    start,length = check(1)
    current = 1
    count = 0
    for _ in range(K):
        if current == start:
            break
        current = A[current]
        count += 1
    if current != start:
        return current
    K = (K-count)%length
    for _ in range(K):
        current = A[current] 
    return current

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

Solution (Python):

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


step_on = [-1] * N
current = 1
min_mv_count = 0
i = 0
for i in range(N + 1):
    
    if i == K:
        print(current)
        exit()
    if step_on[current - 1] == -1:
        step_on[current - 1] = i
        current = A[current - 1]
        i += 1
    else:
        
        period = i - step_on[current - 1]
        pre_mv = i - period
        min_mv_count = pre_mv + ((K - pre_mv) % period)
        
        
        break

current = 1

for i in range(min_mv_count):
    current = A[current - 1]
print(current)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
keiro = [1]
keiro_set = {1}
flag = True
now = 1
start = 0
loopN = 0
loop_list = []
not_loop = False
for i in range(N):
    now = A[now - 1]
    if now in keiro_set:
        start = keiro.index(now)
        loop_list = keiro[start:]
        loopN = len(loop_list)
        break
    else:
        keiro.append(now)
        keiro_set.add(now)
    if i + 2 > K:
        not_loop = True
        break
if not_loop:
    print(keiro[K])
elif K - start >= 0:
    print(loop_list[(K - start) % loopN])
else:
    print(keiro[K])

Solution (Python):



import numpy as np

def next_town(_list,idx):
    return _list[idx]

n, k = map(int, input().split())
a_list = np.array([int(x) for x in input().split()])

t_list = np.zeros(n, dtype=int)

i = 1
count = 0
flag = True
while count < k:
    i = next_town(a_list,i-1)
    count += 1
    if t_list[i-1] == 0:
        t_list[i-1] = count
    elif flag:
        _roop = count - t_list[i-1]
        _tmp = k - count
        count = k - _tmp % _roop
        flag = False

print(i)

Solution (Python):
def main():
  n,k=map(int,input().split())
  a=list(map(int,input().split()))
  b=1
  seen=[-1]*n
  c=0
  while seen[b-1]==-1:
    seen[b-1]=c
    b=a[b-1]
    c+=1
  start=seen[b-1]
  end=c
  k=min(k,start+(k-start)%(end-start))
  b=1
  for _ in range(k):
    b=a[b-1]
  print(b)
if __name__=='__main__':
  main()

Solution (Python):

n,m=list(map(int,input().split(" ")))
 
arr=list(map(int,input().split(" ")))

def bfs(start,n,visited,m):
	
	moves=[]
	moves.append(start)
	visited[start]=1
	br=-1
	
	while(True):

		j=arr[start]-1
		
		if(visited[j]==0):
			moves.append(j)
			visited[j]=1
		
		else:
			br=j
			
			break
		start=j


	
		
	
	if(br!=-1):
		pre=[]
		post=[]
		for i in range(len(moves)):
			if(moves[i]==br):
				pre=moves[:i]
				post=moves[i:]
				break
		if(m<=len(pre)-1):
			print(pre[m]+1)
		else:
			m-=len(pre)
			

			print(post[m%len(post)]+1)


	else:
		
		
		print(moves[m%len(moves)]+1)
visited=[0]*n
bfs(0,n,visited,m)

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

cache = [0]*N

MAP = {}

i=0

cnt=1

rplng = 0
nolp = False
while(True):
    if(cache[i]!=0):
        rplng = cnt - cache[i]
        break
    if(cnt > K):
        nolp = True
        break
    MAP[cnt] = i+1
    cache[i] = cnt
    i = A_s[i]-1
    cnt+=1
if(nolp):
    print(i+1)
else:
    ans = MAP[(K-cnt+1)%rplng+cache[i]]
    print(ans)

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

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

res = [0]
tmp = 0

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

for i in range(n):
    tmp = a[tmp] - 1
    if tf[tmp] != -1:
        start = tmp
        break
    else:
        res.append(tmp)
        tf[tmp] = i+1

lenret = i+1
stridx = tf[start]

cycle = lenret - stridx

if stridx >= k:
    print(res[k]+1)
    exit()
else:
    k = k - stridx

    tmp = k % cycle

    print(res[stridx+tmp]+1)

Solution (Python):

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

ans_list = [1]
history_list = [0 for _ in range(N)]
before_town = 1
loop_start_town = 10 ** 10
for i in range(N):
    now_town = A_list[before_town - 1]
    if history_list[now_town - 1] == 1:
        break
    ans_list.append(now_town)
    before_town = now_town

if len(ans_list) > K:
    print(ans_list[K])
else:
    loop_start_idx = ans_list.index(A_list[ans_list[-1] - 1])
    loop_len = len(ans_list)
    ans_list = ans_list[loop_start_idx:]
    mod_num = (K - loop_len) % (loop_len - loop_start_idx)
    print(ans_list[mod_num])

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

otozureta = set([1])
otozureta_list = [1]

import sys
sys.setrecursionlimit(1000000)

def search(list, next):
    if not otozureta.isdisjoint(set([next])):
        return next
    else:
        otozureta.add(next)
        otozureta_list.append(next)
        return search(list, routes[next - 1])


target = search(routes, routes[0])
target_index = otozureta_list.index(target)

otozureta_list_len = len(otozureta_list)
loop_length = otozureta_list_len - target_index
loop_made_length = target_index


if K < otozureta_list_len:
    print(otozureta_list[K])
else:

    print(otozureta_list[loop_made_length + ((K - loop_made_length) % loop_length)])

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

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

city = 1
route = []
cnt = [0] * n
cnt[0] += 1
route.append(1)


while True:
    city = roads[city-1] 
    cnt[city-1] += 1
    if cnt[city-1] == 2:
        st = route.index(city)
        length = len(route) - st
        break
    route.append(city)


if k < len(route):
    print(route[k])

else:
    amari = (k+1-st) % length
    if amari  == 0:
        print(route[-1])
    else:
        print(route[amari+st-1])

Solution (Python):
N, K = map(int, input().split())
A_list = [-1] + list(map(int, input().split()))
out_loop = [1]
flag = [0, 1] + [0]* (N - 1)
a = A_list[1]
while flag[a] == 0:
    out_loop.append(a)
    flag[a] = 1
    a = A_list[a]
    

        
if K <= (len(out_loop) - 1):
    print(out_loop[K])
else:
    loop = out_loop[out_loop.index(a):]
    k = K - (len(out_loop) - 1)
    k %= len(loop)
    print(loop[k - 1])

Solution (Python):
n, k = map(int, input().split())
a_l = list(map(int, input().split()))
a_m = dict()
tmp = list()  

f = 1

while True:
    if f in a_m:
        
        start = f
        pre = tmp.index(f)
        break
    tmp.append(f)
    t = a_l[f-1]  
    a_m[f] = t  
    f = t

if k > pre:
    cycle_len = len(a_m) - pre
    k_mod = (k - pre) % cycle_len

    result = start

else:
    result = 1
    k_mod = k

for _ in range(k_mod):
    result = a_m[result]

print(result)

Solution (Python):
def main():
  n,k,*a = map(int,open(0).read().split())
  c = [0]
  visit = [False]*n
  visit[0] = True
  for i in range(n):
    nt = a[c[-1]]-1
    if visit[nt]:
      ws = c.index(nt)
      wst = c[:ws]
      wrt = c[ws:]
      wr = len(wrt)
      break
    else:
      c.append(nt)
      visit[nt] = True
  if ws > k:
    ans = wst[k]
  else:
    ans = wrt[(k-ws)%wr]
  print(ans+1)
main()

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

def calc(a, b):
    c = [0] * n
    for i in range(n):
        c[i] = b[a[i]]
    return c

while k:
    if k & 1 == 1:
        x = calc(x, a)
    k //= 2
    a = calc(a, a)

print(x[0]+1)

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

route = [0]
seen = set()
here = 0
for _ in range(N + 100):
    here = A[here]
    route.append(here)

if len(route) >= K:
    print(route[K] + 1)
else:
    for i in range(len(route)):
        if route[i] in seen:
            start = route.index(route[i])
            period = i - start
            
            r = (K - start + 1) % period
            if r == 0:
                idx = period + start - 1
            else:
                idx = r + start - 1
            print(route[idx] + 1)
            break
        seen.add(route[i])

Solution (Python):
n,k = list(map(int,input().split()));
a = list(map(int,input().split()));
i = 0;
start = 0;
count = 0;
finished = [0]*n;
while count < n+2 :
    
    finished[i] = 1;
    i = a[i]-1;
    count += 1;
    if finished[i] :
        start = i;
        break;
    

amari = 0;
if count > n :
    ans = i+1;
else :
    if start == 0 :
        tostart = 0;
    else :
        i=0;
        count = 0;
        while count < n+1 :
            i = a[i]-1;
            count += 1;
            if i == start :
                break;
        tostart = count;
    i=start;
    count = 0;
    while count < n+1 :
        i = a[i]-1;
        count += 1;
        if i == start :
            break;
    if k < count+tostart :
        i = 0;
        for j in range(k) :
            i = a[i]-1;
        ans = i+1;
    else :
        
        amari = (k-tostart)%count;
        i = start;
        for j in range(amari) :
            i = a[i]-1;
        ans = i+1;

print(ans);

Solution (Python):
from sys import stdin

def main():

    input = stdin.readline

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

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

    itta_set = set()
    itta_list = []
    idou_num = 0

    pos = 0

    for i in range(K):
        
        if pos not in itta_set:
            itta_set.add(pos)
            itta_list.append(pos)
        else:
            idou_num = i
            break

        
        pos = A[pos] - 1
    else:
        ans_num = pos + 1
        print(ans_num)
        return

    roop_list = itta_list[itta_list.index(pos):]

    amari = (K - idou_num) % len(roop_list)

    ans_pos = roop_list[amari] + 1

    print(ans_pos)

if __name__ == "__main__":
    main()

Solution (Python):


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

    rireki = []
    loop = ""

    ind = 1
    flags = [0 for _ in range(N)]
    while(1):
        if flags[ind-1] == 1:
            loop = ind
            break
        else:
            rireki.append(ind)
            flags[ind-1] = 1
            ind = As[ind-1]

        
    
    loop_c = len(rireki) - rireki.index(loop)
    if K <= len(rireki)-1:
        print(rireki[K])
    else:
        nokori = K-len(rireki)+1
        ans = nokori % loop_c
        if ans == 0:
            print(rireki[-1])
        else:
            print(rireki[rireki.index(loop)+ans-1])

if __name__ == "__main__":
    main()