Problem:
 Score: 400 points    Problem Statement  The Kingdom of Takahashi has N towns, numbered 1 through N .  There is one teleporter in each town. The teleporter in Town i  (1 \leq i \leq N) sends you to Town A_i .  Takahashi, the king, loves the positive integer K . The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.  Help the king by writing a program that answers this question.      Constraints   2 \leq N \leq 2 \times 10^5  1 \leq A_i \leq N  1 \leq K \leq 10^{18}         Input  Input is given from Standard Input in the following format:  N  K  A_1  A_2  \dots  A_N       Output  Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.        Sample Input 1 4 5
3 2 4 1      Sample Output 1 4  If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4 .       Sample Input 2 6 727202214173249351
6 5 2 5 3 2      Sample Output 2 2

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

flag=[0]*N
patt=[]
i=0
while True:
    patt.append(i)
    if flag[i]==1:
        break
    flag[i]=1
    i=A[i]-1

srt = patt.index(patt[-1])
end = len(patt)-2
ptrn = patt[srt:end+1]

if K<srt:
    print(patt[K]+1)
else:
    B = (K-srt) % len(ptrn)
    print(ptrn[B]+1)

Solution (Python):
import math
N, K = map(int, input().split())
P = [i -1 for i in map(int,input().split())]
lgk = int(math.log(K,2))
last = P
point = 0
for j in range(lgk+1):
    if (K >> j) & 1:
        point = last[point]
    res = []
    for i in last:
        res.append(last[i])
    last = res

print(point+1)

Solution (Python):
def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    prev_p = 1
    g = []
    seen = [0]*N
    i = 0
    while True:
        if seen[prev_p-1]:
            break
        seen[prev_p-1] = i
        g.append(A[prev_p-1])
        prev_p = g[-1]
        i += 1
    g_periodic = g[seen[prev_p-1]:]  
    g_before = g[:seen[prev_p-1]]

    if K <= len(g_before):
        print(g_before[K-1])
    else:
        K_new = (K - len(g_before)) % len(g_periodic)
        print(g_periodic[K_new-1])
if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict

n, k = [0] * 2
a = []

def format_input(filename = None):
	global n, k
	global a
	if filename == None:
		n, k = list(map(int, input().split()))
		a = list(map(int, input().split()))

	elif filename == '__random__':
		from random import randint as rng
		n = rng(2, 2 * 10**5)
		k = rng(1, 10**18)
		a = [rng(1, n) for i in range(n)]
		print(n, k)
		print(' '.join(list(map(str, a))))

def get_answer():
	loop = [1]
	loop_index = defaultdict(int)
	start = -1
	while start == -1 and len(loop) < k + 1:
		node = a[loop[-1]-1]
		if loop_index[node] > 0:
			start = loop_index[node]
		elif node == 1:
			start = 0
		else:
			loop.append(node)
			loop_index[node] = len(loop) - 1

	l = len(loop)
	if k >= l:
		answer = loop[(k - l) % (l - start) + start]
	else:
		answer = loop[k]

	return answer

if __name__ == '__main__':
	format_input()

	ans = get_answer()
	print(ans)

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

def bin(arr,val):
    left,right = 0,len(arr)-1
    while left<=right:
        mid = (left+right)//2
        if arr[mid]==val: return 1
        elif arr[mid]<val: left = mid + 1
        else: right = mid - 1
    return 0

know = []
now = 1
while not bin(know, now):
    know.append(now)
    now = a[now]

start = a[know[-1]]
for i,num in enumerate(know):
    if num == start: loop = know[i:] ; break

ans = know[k] if k<len(know) else loop[(k-len(know))%len(loop)]
print(ans)

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

for i in range(2*n+1000):
    nxt = a[journey[-1]]
    journey.append(nxt)

if k < n+1:
    print(journey[k])
    exit()

loop_end = n
loop_start = n-1

while(journey[loop_start] != journey[loop_end]):
    loop_start -= 1

period = loop_end-loop_start
k %= period

while k < n:
    k += period

print(journey[k])

Solution (Python):
from sys import stdin, setrecursionlimit

setrecursionlimit(10 ** 9)
INF = 1 << 60


def input():
    return stdin.readline().strip()


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

    pos = 1
    order = [-1] * (N+1)
    order[1] = 0
    s = [1]
    for i in range(1, N + 1):
        npos = A[pos-1]
        if i == K:
            print(npos)
            return
        if order[npos] != -1:
            l = order[npos]
            c = i - order[npos]
            break

        order[npos] = i
        s.append(npos)
        pos = npos

    L = l + (K - l) % c
    pos = s[L]

    print(pos)

    return


if __name__ == '__main__':
    main()

Solution (Python):

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


next = 1
List = [-1]*N

for i in range(K):
    if List[next-1] == -1:
        List[next-1] = i
        next = A[next-1]

    else:
        loop = i - List[next-1]
        afterloop = (K-(i-loop))%loop
        print(List.index((i-loop) + afterloop)+1)
        exit()

print(next)

Solution (Python):


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

P=0
L=[0]*int(N+1)
D=[0]*int(N+1)
c=0
R=0
while(1):
    c+=1
    P=A[P]-1
    L[c]=P
    if D[P]>0: 
        R=D[P]
        break
    D[P]=c
    if P==0: break
    

if K < R:
    ans=L[K]+1
else:
    K-=R
    K%=(c-R)
    ans=L[R+K]+1

print(ans)

Solution (Python):
n, k = map(int, input().split())
aaa = list(map(lambda x: int(x) - 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 = aaa[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):
n,k = map(int,input().split())
A = list(map(int,input().split()))
dp = [-1] * (n+1)
B = []
f = 1
c = 0
ans = n
bal = 0
while dp[f-1] == -1:
    dp[f-1] =c
    B.append(f)
    f = A[f-1]
    c +=1
t = B.index(f)
if k>t:
    k -= t
    B = B[B.index(f):]
    k%=len(B)
    print(B[k])
else:
    print(B[k])

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

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

stack = [1]
s = {1}

def dfs(a, k):
  global stack
  global s
  if k == 0:
    return a
  next_a = A[a]
  if next_a in s:
    idx = stack.index(next_a)
    n = len(stack)
    k = (k - 1)%(n - idx)
    return stack[idx + k]
  else:
    stack.append(next_a)
    s.add(next_a)
    res = dfs(next_a, k-1)
  return res

print(dfs(1, K))

Solution (Python):
N,K = map(int, input().split())
A =[0]
B=list(map(int, input().split()))
for m in range(N):
    A.append(B[m])
place=set([])
p=[]
i=1
count=0
while i not in place:
    place.add(i)
    p.append(i)
    i=A[i]
    count+=1
if count>K:
    print(p[K])
else:
    loop=[i]
    start=i
    j=A[i]
    count+=1
    while j!=start:
        loop.append(j)
        j=A[j]
        count+=1
    if count>K:
        print(loop[K-len(p)])
    else:
        num=(K-count)%len(loop)
        print(loop[num])

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

for i in range(n):
  l.append(a[l[i]-1])
p = l.index(l[n])

if k<=n:
  print(l[k])
else:
  x = (k-n+1)%(n-p)
  if x ==0:
    x += (n-p)
    print(l[x-1])
  else:
    print(l[x+p-1])

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

MAX_N=2*10**5
b=[1]
visited=[-1]*(n+10)
for i in range(1,2*MAX_N+1):
    nxt=a[b[-1]]
    b.append(nxt)
        
if k<=n:
    print(b[k])
    exit()

for i,bi in enumerate(b):
    if visited[bi]==-1:
        visited[bi]=i
    else:
        m=i-visited[bi]
        l=visited[bi]
        break
k=k%m

while k<n:
    k+=m
print(b[k])

Solution (Python):
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
i = 0
visit = []
visit_set = set()
while i not in visit_set:
    visit.append(i)
    visit_set.add(i)
    i = A[i] - 1
find = visit.index(i)
if K < find:
    print(visit[K] + 1)
else:
    root = visit[find:]
    K = (K-find) % len(root)
    print(root[K] + 1)

Solution (Python):
N,K = map(int,input().split())
As = list(map(int,input().split()))
towns = [0]*N
route = [0]
pre = 0
i = 0
towns[0] = 1
for _ in range(K):
    i = As[i]-1
    if towns[i]>0:
        pre = route.index(i)
        route = route[pre:]
        break
    route.append(i)
    towns[i] = 1
mod = len(route)
print(route[(K-pre)%mod]+1)

Solution (Python):
from sys import stdin
N,K=list(map(int,(stdin.readline().strip().split())))
A=list(map(int,(stdin.readline().strip().split())))
cycle=[1]
count=[0]*N
tele=0
count[tele] += 1
while(True):
    cycle.append(A[tele])
    tele=A[tele]-1
    count[tele] += 1
    if count[tele] == 2:
        break
a=cycle.index(tele+1)
if K<len(cycle):
    print(cycle[K])
else:
    num=len(cycle[a:-1])
    num=(K-len(cycle[:a]))%num
    print(cycle[num+len(cycle[:a])])

Solution (Python):
from sys import stdin, setrecursionlimit

setrecursionlimit(10 ** 9)
INF = 1 << 60


def input():
    return stdin.readline().strip()


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

    pos = 1
    order = [-1] * (N+1)
    order[1] = 0
    s = [1]
    for i in range(1, N + 1):
        npos = A[pos-1]
        if order[npos] != -1:
            l = order[npos]
            c = i - order[npos]
            break

        order[npos] = i
        s.append(npos)
        pos = npos

    if (K < l):
        print(s[K])
    else:
        print(s[l + (K - l) % c])

    return


if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = []
ord = [-1 for i in range(n+1)]
v = 1
c = 1
l = 0
while ord[v] == -1:
    ord[v] = len(s)
    s.append(v)
    v = a[v-1]
c = len(s) - ord[v]
l = ord[v]
if k < l:
    print(s[k])
else:
    k -= l
    k %= c
    print(s[l+k])

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

def bin(arr,val):
    left,right = 0,len(arr)-1
    while left<=right:
        mid = (left+right)//2
        if arr[mid]==val: return 1
        elif arr[mid]<val: left = mid + 1
        else: right = mid - 1
    return 0

know = []
now = 1
while not bin(know, now):
    know.append(now)
    now = a[now]

loop_start = a[know[-1]]
for i,num in enumerate(know):
    if num == loop_start:
        loop_init = i
        loop = know[i:]
        break



cnt = len(loop)
if k < len(know):
    ans = know[k]
else:
    ans = loop[(k-loop_init)%cnt]



print(ans)

Solution (Python):
import sys
n,k=map(int,input().split())
a=[int(x) for x in input().split()]
vis_ti=[-1]*n
vis_at=[0]
now=0
for i in range(1,k+1):
  now=a[now]-1
  if vis_ti[now]>=0:
    bgn=vis_ti[now]
    print(vis_at[bgn+(k-bgn)%(i-bgn)]+1)
    sys.exit()
  vis_ti[now]=i
  vis_at.append(now)
print(vis_at[-1]+1)

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
A_dict = {i:a for i,a in enumerate(A,1)}

History = [1]
History_set = {1}
now = 1
for i in range(N):
    now = A_dict[now]
    if now not in History_set:
        History.append(now)
        History_set.add(now)
    else:
        break

if K < i:
    print(History[K])
else:
    e = History.index(now)
    
    
    loop_num = len(History[e:])
    
    num = (K-e)%loop_num
    
    print(History[e:][num])

Solution (Python):
def main():
    n, k, *a = map(int, open(0).read().split())
    a = [0] + a
    root = [1]
    visited = [False for _ in range(n+1)]
    nx = 1
    visited[1] = True

    step = 0
    while True:
        step += 1
        now = nx
        nx = a[now]
        if step == k:
            print(nx)
            break
        if visited[nx]:
            end = step
            start = root.index(nx)
            d = end - start
            r = k - step
            index = start + r % d
            print(root[index])
            break

        visited[nx] = True
        root.append(nx)

if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
A = [a - 1 for a in A]
D = 60
MAX_N = 200005
to = [[0] * MAX_N for _ in range(D)]
for i, a in enumerate(A):
    to[0][i] = a

for i in range(D - 1):
    for j in range(N):
        to[i + 1][j] = to[i][to[i][j]]

v = 0
for i in range(D - 1, -1, -1):
    l = 1 << i
    if l <= K:
        v = to[i][v]
        K -= l
print(v + 1)

Solution (Python):
n,m  = map(int,input().split())
a = [int(x) for x in input().split()]

ans1 = [1]
temp = 0
visit = [0]*(n+1)
visit[1] = 1
while(True):
    ans1 += [a[temp]]

    if visit[a[temp]] == 1:
        break

    visit[a[temp]] = 1
    temp = a[temp]-1


    if len(ans1) == m+1:
        print(ans1[len(ans1)-1])
        exit()


num1 = ans1.index(a[temp])
ans2 = ans1[num1:len(ans1)-1]

num = len(ans2)

print(ans2[(m-num1)%num])

Solution (Python):
n, k = map(int, input().split())
A = list(map(int, input().split()))
D = [0] * (n+1)
now = 1
for i in range(1, k+1):
    tmp = A[now-1]
    if not D[tmp]:
        now = tmp
        D[now] += i
    else:
        pre = D[tmp]
        loop = i - D[tmp]
        if loop>1:
            now=D.index((k - pre) % loop + pre)
        else:
            now=tmp
        break
print(now)

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = []
x = [0] * n
x.append(0)
v = 1
c = 1
l = 0
while x[v] == 0:
    x[v] = len(s)
    s.append(v)
    v = a[v-1]
c = len(s) - x[v]
l = x[v]


if k < l:
    print(s[k])
else:
    k -= l
    k = k % c
    print(s[l+k])

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

def bin(arr,val):
    left,right = 0,len(arr)-1
    while left<=right:
        mid = (left+right)//2
        if arr[mid]==val: return 1
        elif arr[mid]<val: left = mid + 1
        else: right = mid - 1
    return 0

know = []
now = 1
while not bin(know, now):
    know.append(now)
    now = a[now]

start = a[know[-1]]
for i,num in enumerate(know):
    if num == start: loop = know[i:] ; break



if k < len(know):
    ans = know[k]
else:
    k -= len(know)
    ans = loop[k%len(loop)]

print(ans)

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

li = [-1] * n
li[0] = 0
town = [0]
now = 0
flag = False

for i in range(k):
    now = a[now] - 1
    if li[now] != -1:
        s = li[now]
        break
    else:
        li[now] = i + 1
        town.append(now)
    if i == k-1:
        flag = True

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

town2 = town[s:]
m = len(town2)
l = len(town) - len(town2)

print(town2[(k - l) % m]+1)

Solution (Python):



def input_int():
    return int(input())



def int1(x):
    return int(x) - 1



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



def input_to_int_tuple():
    return tuple(map(int, input().split()))



def input_to_int_tuple_minus1():
    return tuple(map(int1, input().split()))


def main():
    n, k = input_to_int_map()
    a = {i + 1: int(val) for i, val in enumerate(input().split())}

    place = 1
    visit = {place}
    place_visits = [place]
    for i in range(k):
        place = a[place]
        if place in visit:
            left = place_visits.index(place)
            loop_list = place_visits[left:]
            return loop_list[(k - left) % len(loop_list)]
        else:
            visit.add(place)
            place_visits.append(place)

    return place


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

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

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

visited = [-1] * n
now = 0
visited[0] = 0
pre_roop = 0
pos = 0
i = 1
r = 1
while i <= k:
    next = a[now]
    
    if visited[next] >= 0:
        r = i-visited[next]
        pre_roop = visited[next]
        pos = next
        
        
        break
    else:
        visited[next] = i
        now = next
        
        i += 1

if i > k:
    print(now + 1)
else:
    l = (k - pre_roop) % r
    
    i = 0
    p = pos
    while i < l:
        p = a[p]
        i +=1

    print(p+1)

Solution (Python):



def input_int():
    return int(input())



def int1(x):
    return int(x) - 1



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



def input_to_int_tuple():
    return tuple(map(int, input().split()))



def input_to_int_tuple_minus1():
    return tuple(map(int1, input().split()))


def main():
    n, k = input_to_int_map()
    a = {i + 1: int(val) for i, val in enumerate(input().split())}

    place = 1
    visit = {place}
    place_visits = [place]
    for i in range(k):
        place = a[place]
        if place in visit:
            left = place_visits.index(place)
            return place_visits[left + (k - left) % (i + 1 - left)]
        else:
            visit.add(place)
            place_visits.append(place)

    return place


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

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

history = []
is_visited = [False] * n

index = 0
cnt = 0
loop_start_city_index = 0
for i in range(k+1):
    if i == k:
        print(index+1)
        exit()

    if is_visited[index]:    
        loop_start_city_index = index
        break
    
    is_visited[index] = True
    history.append(index)
    index = a[index] - 1
    cnt += 1

from_start_to_loop_start = history.index(loop_start_city_index)
loop_length = len(history) - from_start_to_loop_start

print(history[from_start_to_loop_start + (k-from_start_to_loop_start)%loop_length] + 1)

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
lity=[[0,0] for i in range(N)]
if N<K:
  hata=True
  i=0
  a=0
  j=0
  while hata:
    if lity[i][0]==1:
      a=j-lity[i][1]
      break
    lity[i][0]+=1
    lity[i][1]=j
    i=A[i]-1
    j+=1
    
  K-=j
  p=K%a
  while p>=1:
    i=A[i]-1
    p-=1
  print(i+1)
else:
  i=0
  for j in range(K):
    i=A[i]-1
  print(i+1)

Solution (Python):
N, K = map(int, input().split())
A = [0] + list(map(int, input().split()))
 
s = [0] * (N+1)
p = 1
h = []
for i in range(K):
    h.append(p)
    s[p] = 1
    p = A[p]

    if s[p] != 0:
        break

if i == K-1:
    print(p)
    exit()
else: 
    period = len(h) - h.index(p)
    rem = (K - h.index(p)) % period
    print(h[h.index(p):][rem])

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

visited = [False for _ in range(N)]
now = 0

cycle = []

while True:
    cycle.append(now)
    visited[now] = True
    now = A[now] - 1

    if visited[now]:
        break

total_len = len(cycle)

cycle_start = 0

for i in range(total_len):
    if cycle[i] == now:
        cycle_start = i
        break

cycle_len = total_len - cycle_start

if K < cycle_start:
    print(cycle[K] + 1)
else:
    print(cycle[cycle_start + (K - cycle_start) % cycle_len] + 1)

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

  current = 0
  if K < N:
    for i in range(K):
      current = A[current]
    print(current + 1)
    return True
  else:
    history = [False] * N
    load_map = []
    while True:
      load_map.append(current)
      current = A[current]
      if history[current]:
        loop_length = len( load_map[load_map.index(current):] )
        if loop_length == 0:
          print(current + 1)
          return True

        length_to_loop = len( load_map[:load_map.index(current)] )
        additional_way = (K-length_to_loop)%loop_length
        print(load_map[length_to_loop + additional_way] + 1)
        return True
      else:
        history[current] = True

if __name__ == "__main__":
    resolve()

Solution (Python):
def main(N, K, A):
    i = 0   
    lst_memo = []
    set_memo = set([])
    while i not in set_memo:
        lst_memo.append(i)
        set_memo.add(i)
        i = A[i] - 1    
    key = lst_memo.index(i)
    if K < key:
        print(lst_memo[K] + 1)
    else:
        roop = lst_memo[key:]
        print(roop[(K - key) % len(roop)] + 1)    


if __name__ == '__main__':
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))
    main(N, K, A)

Solution (Python):
import sys
from collections import Counter
from collections import deque
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

n,k=mp()
a=lmp()
l=[]
i=0
ch=[0]*(n+1)
while True:
    if ch[i]==1:
        break
    else:
        ch[i]=1
        l.append(a[i])
        i=a[i]-1


x=l.index(a[i])
y=len(l)-x

if k<=x:
    print(l[k-1])
else:
    print(l[(k-x-1)%y+x])

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

done = [1]
donedic = {}
donedic[1] = 1
now = 1
for i in range(1,N+1):
    nexttown = A[now-1]
    
    try:
        a = donedic[nexttown]
    except:
        donedic[nexttown] = 1
        done.append(nexttown)
        now = nexttown
    else:
        break

start = done.index(nexttown)
end = len(done)-1
before = start 
loop = done[start:]

if K < before:
    saisyuu = done[K]
else:
    nokori = K-before
    n_loop = int(nokori/len(loop))
    loopfirst = done[start]
    hasuu = nokori%len(loop)
    saisyuu = loop[hasuu]
    
    
    
print(saisyuu)

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

visited = [False for _ in range(N)]

A = list(map(lambda n: int(n)-1, input().split()))
tmp = 0 
visited[0] = True

log = [0] 

for i in range(1, K+1):
    tmp = A[tmp]
    if visited[tmp]:
        start = log.index(tmp)
        break

    visited[tmp] = True
    log.append(tmp)

if i == K:
    print(tmp+1)
else:
    loop = log[start:i+1]
    period = len(loop)
    remain = K - i
    print(loop[remain%period] + 1)

Solution (Python):
from collections import deque
import numpy as np
n, k = map(int, input().split())
An = list(map(int, input().split()))
root = deque([1])
check = np.zeros(n, np.int)
check[0] = 1
i = 0
dup = 1
cnt = 1
for _ in range(n):
    temp = An[i]
    if check[temp-1] == 1:
        dup = temp
        break
    root.append(temp)
    check[temp-1] = 1
    i = temp - 1
    cnt += 1
index = root.index(dup)
if index >= k:
    print(root[k])
elif index == cnt - 1:
    print(dup)
else:
    print(root[(k-index) % (cnt-index) + index])

Solution (Python):
n,k = map(int, input().split())
a = list(map(int, input().split()))
import numpy as np
link = set()
next = a[0]
link.add(1)
while next not in link:
    link.add(next)
    next = a[next-1]


link2 = set()
next2 = a[0]
link2.add(1)
while next not in link2:
    link2.add(next2)
    next2 = a[next2-1]

link2.remove(next)
ans = 0

rep = len(link) - len(link2)

if (len(link2) == 0):
    p = k%rep
    
    for i in range(p+rep):
        next = a[next-1]
elif(k > len(link2)):
    
    p = (k-len(link2))%rep
    
    
    for i in range(p+rep):
        next = a[next-1]
else:
    
    next = a[0]
    for i in range(k-1):
        next = a[next-1]

ans = next

print(ans)

Solution (Python):
N,K = list(map(int, input().split()))
A = list(map(int, input().split()))
r = 0
if K <= N:
    current = 1
    for i in range(K):
        current = A[current-1]
    print(current)
else:
    isReturn = [0 for i in range(N)]
    step = 1
    current = 1
    isReturn[current-1] = step
    for i in range(N):
        current = A[current-1]
        step += 1
        if isReturn[current-1] == 0:
            isReturn[current-1] = step
        else:
            r = step - isReturn[current-1]
            break
    
    t = ((K-step) % r) + 1
    for i in range(t):
        current = A[current-1]
        
    print(current)

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

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

visited = [1]
is_visited = [0] * n
now = 1
step = 0
for i in range(k):
    now = a[now-1]
    step += 1
    if is_visited[now-1] == 0:
        is_visited[now-1] = 1
        visited.append(now)
    else:
        ind = visited.index(now)
        loop = visited[ind:]
        tmp = (k-step) % len(loop)
        now = loop[tmp]
        break

print(now)

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

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

l=[1]
di={}
di[1]=1

for i in a:
    b=a[l[-1]-1]
    if b in di:
        x=b
        break
    l.append(b)
    di[b]=1
t1=0
for j in l:
    if j==x:
        break
    else:
        t1+=1

t2=len(l)-t1
if k<=t1:
    print(l[k])

else:
    aa=(k-t1)%t2
    print(l[t1+aa])

Solution (Python):
from math import *
from collections import *
from itertools import *
from bisect import *
from operator import *
import sys
sys.setrecursionlimit(1000000)
def io():
    return map(int,input().split())
def op():
    return list(map(int,input().split()))
def o():
    return int(input())
def kl(con,x=0):
    if x==0:print('Yes') if con else print('No')
    elif x==1:print('yes') if con else print('no')
    elif x==2:print('YES') if con else print('NO')

MOD =    1000000007
MAX=2147483647
MIN=-2147483648
p=input
l,l1,l2,l3=[],[],[],[]

n,k=io()
l=op()
x=y=0
i=0
fr=[0]*(200002)
while 1:
    if fr[l[i]]==0:
        l1.append(l[i])
        fr[l[i]]=1
        i=l[i]-1
    else:
        y=l1.index(l[i])
        x=len(l1)-y
        break
if k<=len(l1):
    print(l1[k-1])
else:
    k-=y
    k%=x
    if k==0:
        k=x
    print(l1[y+k-1])

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

n, k = (int(x) for x in input().split())
seq = [int(x) for x in input().split()]
visited = [[False,0] for _ in xrange(n)]

t = 1
cnt = 0
if n < k:
    while not visited[t-1][0]:
        visited[t-1][0] = True
        visited[t-1][1] = cnt
        t = seq[t-1]
        cnt += 1

    cycle_len = cnt - visited[t-1][1]
else:
    cycle_len = n
for _ in xrange((k-visited[t-1][1]) % cycle_len):
    t = seq[t-1]
print(t)

Solution (Python):
n,k = list(map(int,input().split()))
A = list(map(int,input().split()))
tour=[0]
visited=[0]*n
visited[0]=1
next_town = 0
flag=False
for i in range(n):
    next_town=A[next_town]-1
    if i+1==k:
        flag = True
        ans = next_town
        break
    if next_town==0:
        first_roop_idx = 0
        break
    if visited[next_town]>0:
        first_roop_idx = visited[next_town]
        break
    tour.append(next_town)
    visited[next_town]=i+1



if not flag:
    if k<=len(tour):
        ans = tour[k]
    else:
        k-=first_roop_idx
        
        if len(tour)-first_roop_idx==0:
            k=0
        else:k=k%(len(tour)-first_roop_idx)
        
        ans = tour[first_roop_idx+k]
print(ans+1)

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

A = [0] + A

dp = [A]
for k in range(1, 100):
    dp.append([0])  
    for i in range(1, N + 1):
        
        j = dp[k - 1][i]
        
        dp[k].append(dp[k - 1][j])
ans = 1
for k in range(100):
    if K & 2 ** k > 0:
        ans = dp[k][ans]
        K -= 2 ** k
print(ans)

Solution (Python):
from queue import Queue

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

    visited = [False] * N
    visited[0] = True
    p = [1]
    l = []
    r = []

    while(len(p) < N):
        v = p[-1] - 1
        n = A[v] - 1

        if(visited[n]):
            d = p.index(n+1)
            l = p[0:d]
            r = p[d:]
            break

        p.append(A[v])
        visited[n] = True

    if(len(l) == 0 and len(r) == 0):
        print(p[K%len(p)])
    else:
        if(K < len(p)):
            print(p[K])
        else:
            k = K - len(l)
            k %= len(r)
            print(r[k])
        

if __name__ == "__main__":
    main()

Solution (Python):


import sys
readline = sys.stdin.readline

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

route = [0]
visited = {0}
while True:
  nex = A[route[-1]] - 1

  if nex in visited:

    loopstart = route.index(nex)

    break
  else:
    visited.add(nex)
    route += [nex]
    


before_loop,one_loop = route[:loopstart],route[loopstart:]



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

Solution (Python):
import sys

n, k = map(int, input().split(" "))
a = [-1] + list(map(int, input().split(" ")))

i = 1
head = []
used = {}
roop = []

index = 0
for _ in range(k):
    index += 1
    i = a[i]
    if i in used:
        head = [ k for k, v in sorted(used.items(), key=lambda x:x[1]) if v < used[i]]
        roop = [ k for k, v in sorted(used.items(), key=lambda x:x[1]) if v >= used[i]]
        if len(head) >= k:
            print(head[k-1])
        else:
            x = (k - 1 - len(head)) % len(roop)
            print(roop[x])
            sys.exit()
    else:
        used[i] = index

print([ k for k, v in sorted(used.items(), key=lambda x:x[1])][k-1])

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

s = {0}
loop = [0]

while a[loop[-1]] not in s:
    loop.append(a[loop[-1]])
    s.add(loop[-1])

    
idx = loop.index(a[loop[-1]])

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

Solution (Python):
n,k=map(int, input().split())
a=[int(x)-1 for x in list(input().split())]
way=[0]
seen=[0 for i in range(n)]
while True:
        now=way[-1]
        way.append(a[now])
        
        if seen[a[now]]==1:
                break
        seen[a[now]]=1


last=way[-1]
st=way.index(last)
en=len(way)-1
step=en-st
rest=(k-st+1)%step
if k>=st:
        if rest==0:
                ans=way[st-1+step]+1
        else:
                ans=way[st-1+rest]+1

else:
        ans=way[k]+1
print(ans)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
memo = [-1] * (N+1)
checked_num = {1:None}
memo[0] = 1

teleporter = A[0]
memo[1] = teleporter
checked_num[memo[1]] = None
repeat_point = -1
flag = False

for i in range(2, N+1):
    
    memo[i] = A[teleporter-1]
    teleporter = A[teleporter-1]
    if memo[i] in checked_num and flag == False:
        repeat_point = i
        flag = True
    checked_num[memo[i]] = None



start_point = memo.index(memo[repeat_point])
repeat = repeat_point - start_point


if K <= N:
    print(memo[K])
else:
    mod = (K-start_point) % repeat
    
    print(memo[mod+start_point])

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
t_l = 0
while True:
    nex = data[nex]-1
    if visited[nex] is True:
        break
    else:
        visited[nex] = True
        t_l += 1
start = nex
cycle = 1
c = [start]
while True:
    nex = data[nex]-1
    if nex == start:
        break
    else:
        cycle += 1
        c.append(nex)
before = t_l - cycle + 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):
N, K = map(int, input().split())
A = list(map(int, input().split()))
 
B = []
Vector = [0]*N
j = 0
 
for i in range (0,K):
	if Vector[A[j]-1] == 1:
		Value = B.index(A[j])
		C = B[B.index(A[j])::]
		break
	else:
		B.append(A[j])
		Vector[A[j]-1] = 1
		j = A[j]-1

if A[0] ==1:
	print(1)
elif len(B) == K:
	print(B[-1])
else:
	print(C[(K-Value-1)%len(C)])