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
sys.setrecursionlimit(10**6)

n, k = map(int, input().split())
A = list(map(int, input().split()))
L = [1]
S = {1}

def f(L, S):
    last = L[-1]-1
    if A[last] not in S:
        L.append(A[last])
        S |= {A[last]}
        return f(L, S)
    else:
        return L
P = f(L, S)
a = A[P[-1]-1]
j = P.index(a)
r = len(P)
l = r - j

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

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

    
    
    
    now = 0
    history = [0]
    isVisited = [False for i in range(N)]
    i = 0
    while i<K:
        
        now = A[now]-1
        
        
        if isVisited[now] == False:
            history.append(now)
            isVisited[now] = True
            i+=1
        
        else:
            start = history.index(now)
            r = start + (K-1-i)%(len(history)-start)
            now = history[r]
            break

    print(now+1)

main()

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

s=[]
o=[-1]*(n+1)
i=1
c=1
l=0
while o[i] == -1:
    o[i] = len(s)
    s.append(i)
    i = a[i-1]
    
c=len(s) - o[i]
l=o[i]
if k < l:
    print(s[k])
else:
    k -= l
    k %= c
    print(s[l+k])

Solution (Python):
n,k = map(int,input().split())
a = list(map(int,input().split()))
p = a[0]
s = a[0]
g = [1]
q = []
for i in range(n+1):
    g.append(p)
    p = a[p-1]
g.reverse()
for i in range(n):
    if g[0] == g[i+1]:
        mod = i+1
        break
g.reverse()
for i in range(len(g)):
    if g[i] == g[i + mod]:
        d = i
        break
if k <= n:
    for i in range(k):
        q.append(s)
        s = a[s-1]
    q.reverse()
    print(q[0])
else:
    print(g[d+(k-d)%mod])

Solution (Python):
N, K = map(int, input().split())
A = list(i - 1 for i in map(int, input().split()))
ans = 0
count = 0
X = [-1] * N
Y = - 1
while count < K:
  if X[ans] == -1:
    X[ans] = count
    ans = A[ans]
    count += 1
  else:
    Y = X[ans] + (K - count) % (count - X[ans])
    break
if Y == -1:
  print(ans + 1)
else:
  print(X.index(Y) + 1)

Solution (Python):

import sys

sysread = sys.stdin.readline
read = sys.stdin.read


sys.setrecursionlimit(10**7)
import math


import numpy as np
def run():
    N,K = map(int, sysread().split())
    A = [0] + list(map(int, sysread().split()))

    seen = [False] * (N+1)
    arr = [1]
    seen[1] = True
    while True:
        next = A[arr[-1]]
        if seen[next]:
            arr.append(next)
            break
        arr.append(next)
        seen[next] = True
    arr = np.array(arr)
    x = int(math.log2(K)) + 1
    dub = np.array([[0] * (N+1) for _ in range(x)])
    dub[0, arr[:-1]] = np.array(arr[1:])
    for d in range(1,x):
        next1 = dub[d-1, arr[:-1]]
        next2 = dub[d-1, next1]
        dub[d, arr[:-1]] = next2

    ret = 1
    while K:
        d = int(math.log2(K))
        K -= 1 << d
        ret = dub[d][ret]
    print(ret)

if __name__ == "__main__":
    run()

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
def f(x,dic,i):
    p=dic1[x]
    if p in dic:
        return [dic,p]
    else:
        dic[p]=i
        return f(p,dic,i+1)

def inv(x,dic):
    for k,v in dic.items():
        if v==x:
            return k

n,k=map(int,input().split())
m=[i for i in range(n)]
l=list(map(int,input().split()))
for i in range(n):
    l[i]-=1
dic1=dict(zip(m,l))
d={0:0}
trace1=f(0,d,1)
u=trace1[0]
i=len(u)
if k<i:
    print(inv(k,u)+1)
else:
    d={trace1[1]:0}
    trace2=f(trace1[1],d,1)
    v=trace2[0]
    j=len(v)
    k=k-i
    k=k%j
    print(inv(k,v)+1)

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

s=[]
ord=[-1]*(N+1)
c=1
l=0
v=1
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):
N,K = map(int,input().split())
A = [0] + list(map(int,input().split()))
turn = [-1] * (N+1) 
c = 1
for k in range(K):
    if turn[c]!=-1:
        T = k - turn[c] 
        bias = turn[c] 
        break
    turn[c] = k
    c = A[c]
else:
    print (c)
    exit()

K -= bias 
K %= T
K += bias
c = 1 
for k in range(K):
    c = A[c]
print (c)

Solution (Python):
from collections import defaultdict
n,k=map(int,input().split())
l=list(map(int,input().split()))
d=defaultdict(int)
for i in range(n):
    d[i+1]=l[i]
visited=set()
l=[]
i=1
while True:
    l.append(i)
    if i not in visited:
        visited.add(i)
    else:
        break
    i=d[i]
first=l.index(l[-1])
if k<first:
    print(l[k])
else:
    k=(k-first)%((len(l)-1)-first)
    k+=first
    print(l[k])

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

dic={}
kaisi=1
for i in range(1,n+1):
  if kaisi in dic:
    st=dic[kaisi]
    gl=i
    break
  else:
    dic[kaisi]=i
  kaisi=a[kaisi-1]

if k<st:
  kaisi=1
  for i in range(0,k):
    kaisi=a[kaisi-1]
  print(kaisi)
else:
  kaisuu=(k-st+1)%(gl-st)+st-1
  kaisi=1
  for i in range(0,kaisuu):
    kaisi=a[kaisi-1]
  print(kaisi)

Solution (Python):
def doubling_numpy():
    import numpy as np
    N, K = map(int, input().split())
    D = K.bit_length()
    U = N + 1
    dbl = np.zeros((D, U), dtype=np.int64)
    dbl[0, 1:] = np.array(input().split(), dtype=np.int64)

    for d in range(D - 1):
        dbl[d+1] = dbl[d, dbl[d]]

    v = 1
    for i in reversed(range(D)):
        if K & (1 << i):
            v = dbl[i, v]
    print(v)


if __name__ == "__main__":
    doubling_numpy()

Solution (Python):
n,k=list(map(int,input().split()))
A=list(map(int,input().split()))
start,steps=1,0
root=dict()

while start not in root and steps < k:
  root[start]=steps
  steps+=1
  start=A[start-1]

if steps == k:
  print(start)
else:
  pa = steps-root[start]
  ans= root[start] + (k-steps)%pa
  root={v: k for k, v in root.items()}
  print(root[ans])

Solution (Python):






import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string


BUFSIZE = 8192

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def main():
    nk=list(map(int,input().split()))
    n,k=nk[0],nk[1]
    A=list(map(int,input().split()))
    pos=[1]
    cnt=0
    s=set()
    s.add(1)
    while cnt<len(A):
        temp=A[pos[-1]-1]
        pos.append(temp)
        
        
        if temp in s:
            
            break
        s.add(temp)
        cnt+=1
    
    index=pos.index(pos[-1])
    if k<index:
        print (pos[k])
    else:
        mod=(k-index)%(len(pos[index:])-1)
        
        print (pos[index+mod])
if __name__ == "__main__":
    main()

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

already = [False] * N
step = 0
now = 1
count = 0
while(already[now-1] != True):
    already[now - 1] = True
    now = A[now - 1]
    count += 1
    if count == K:
      print(now)
      exit(0)
loop = 0
cycle = 0
if(now == 1):
    step = 0
    cycle = count
    loop = K % cycle
else:
    step = 0
    temp = 1
    while(temp != now):
        temp = A[temp - 1]
        step += 1
    cycle = count - step
    loop= (K - step) % cycle

temp = 1
for i in range(step + loop):
    temp = A[temp - 1]
print(temp)

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

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

  
  s = []

  
  v = 1

  
  while(o[v] == -1):
    
    o[v] = len(s)
    s.append(v)
    v = A[v - 1] 

  
  l = o[v]
  
  c = len(s) - l

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


if __name__ == "__main__":
  main()

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

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

while K:
  if K & 1:
    now = A[now]
  nex = [0] * (N + 1)
  for i in range(N + 1):
    nex[i] = A[A[i]]
  A = nex
  K >>= 1
  
print(now)

Solution (Python):
import sys

def inp(): return int(sys.stdin.readline())
 
def inp_list(): return list(map(int, sys.stdin.readline().split()))

N, K = inp_list()
A = inp_list()
A = list(map(lambda x: x - 1, A)) 



pos = 0 


visited = [False for _ in range(N)]
teleport_count = {}
distance = 0
l_pos = 0
tel_cnt = 0
while True:
    nxt = A[pos]
    
    if visited[nxt]:
        
        r_pos, l_pos = teleport_count[pos], teleport_count[nxt]
        distance = r_pos - l_pos
        break
    tel_cnt += 1
    
    teleport_count[nxt] = tel_cnt
    
    visited[nxt] = True
    
    pos = nxt

def get_key_from_value(val, d):
    for k, v in d.items():
        if v == val:
            return k






if K <= l_pos:
    
    print(get_key_from_value(K, teleport_count) + 1)
else:
    diff = K - l_pos
    rem = diff % (distance + 1)
    ans_pos = l_pos + rem
    
    print(get_key_from_value(ans_pos, teleport_count) + 1)

Solution (Python):
n, k = map(int, input().split())
A = list(map(int, input().split()))
A = [-1] + A
memo = []
loop = []
visit = [0]*n
town = 1
while visit[town-1] < 2:
    if visit[town-1] == 0:
        memo.append(town)
    else:
        loop.append(town)
    visit[town-1] += 1
    town = A[town]
outlier = len(memo) - len(loop) 
T = len(loop)
if k <= outlier:
    print(memo[k])
else:
    print(loop[(k-outlier) % T])

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,k = inpl()
a = inpl()
now = 1
r = [1]
fin = set([1])
while True:
    now = a[now-1]
    if now in fin:
        break
    r.append(now)
    fin.add(now)
ln = len(r)
for i in range(ln):
    if now == r[i]:
        fir = r[:i]
        nxx = r[i:]
        break
if k < i:
    print(fir[k])
else:
    k -= i
    m = len(nxx)
    print(nxx[k%m])

Solution (Python):

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


already = [False] * N
step = 0
now = 1
count = 0
while(already[now-1] != True):
    already[now - 1] = True
    now = A[now - 1]
    count += 1
    if count == K: 
      print(now)
      exit(0)






loop = 0
cycle = 0
if(now == 1):
    step = 0
    cycle = count
    loop = K % cycle
else:
    step = 0
    temp = 1
    while(temp != now):
        temp = A[temp - 1]
        step += 1
    cycle = count - step
    loop= (K - step) % cycle

temp = 1
for i in range(step + loop):
    temp = A[temp - 1]
print(temp)

Solution (Python):
import collections
n,k = map(int,input().split())
a = list(map(int,input().split()))
list = [1]
i = 0
num = a[0]
for i in range(3*n):
    list.append(num)
    num = a[num-1]

cnt = collections.Counter(list)
onevalue = [k for k,v in cnt.items() if v == 1]
lstart = len(onevalue)
lroop = len(set(list))-lstart

if k <= lstart:
    num = a[0]
    for i in range(k-1):
        num = a[num-1]
    print(num)
    exit()
elif lstart == 0:
    k = (k-lstart)%lroop
    num = 1
    for i in range(k):
        num = a[num-1]
    print(num)
    exit()
else:
    k = (k-lstart)%lroop
    num = a[0]
    if lstart > 0:
        for i in range(lstart-1):
            num = a[num-1]
    for i in range(k):
        num = a[num-1]
    print(num)
    exit()

Solution (Python):

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


time = [-1 for _ in range(N+10)]


new = 1
t = 0


while time[new] == -1:
    time[new] = t
    new = A[new - 1]
    t += 1


line = time[new]
loop = t - time[new]



if K > line:
    K = (K - line) % loop
    for i in range(N+1):
        time[i] -= line

for i in range(N+1):
    if time[i] == K:
        print(i)
        break

Solution (Python):

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


already = [False] * N
step = 0
now = 1
count = 0
while(already[now-1] != True):
    already[now - 1] = True
    now = A[now - 1]
    count += 1
    if count == K:
      print(now)
      exit(0)




loop = 0
cycle = 0
if(now == 1):
    step = 0
    cycle = count
    loop = K % cycle
else:
    step = 0
    temp = 1
    while(temp != now):
        temp = A[temp - 1]
        step += 1
    cycle = count - step
    loop= (K - step) % cycle

temp = 1
for i in range(step + loop):
    temp = A[temp - 1]
print(temp)

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = [i-1 for i in a] 
path = [] 
now = 0
visited = [False] * n

while not visited[now]:
    path.append(now)
    visited[now] = True
    now = a[now]



s = path.index(now)
length_loop = len(path) - s

if k < s:
    print(path[k]+1)
else:
    print(path[(k-s)%length_loop+s]+1)

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

stack=[]
done=[0 for i in range(2*(10**5))]
done[0]=0
now=0
dou=[]

while(done[now]<2):
  
  if done[now]==0:
    stack.append(now)
  else:
    dou.append(now)
  done[now]+=1
  now=A[now]-1

if K<len(stack):
  print(stack[K]+1)
else:
  print(dou[(K-len(stack)-len(dou))%len(dou)]+1)

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

    pos = 0
    while K > 0:
        if K&1:
            pos = a[pos]
        
        a = [a[a[i]] for i in range(N)]
        K >>= 1
    print(pos+1)


if __name__ == '__main__':
    main()

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
l1=[0]*n
l1[0]+=1
c=0 
now=0
ne=a[now]-1 
while True:
    if c==k:
        print(now+1)
        exit()
    if l1[ne]==0:
        l1[ne]+=1
        now=ne
        ne=a[now]-1
        c+=1
    else:
        now=ne
        ne=a[now]-1
        c+=1
        break

roop_c=0
while True:
    if c+roop_c==k:
        print(now+1)
        exit()
    if l1[ne]==1:
        l1[ne]+=1
        now=ne
        ne=a[now]-1
        roop_c+=1
    else:break

re=(k-c)%roop_c
if re==0:print(now+1)
else:
    for i in range(re):
        if i==re-1:print(ne+1)
        ne+=-ne+a[ne]-1

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

count = [0]*n
loop_st = 0
for town in path:
    count[town-1] += 1
    if count[town-1] == 2:
        loop_st = town
        break
loop_st_idx = path.index(loop_st)
loop_fin_idx = path.index(loop_st, loop_st_idx+1)

if k >= loop_st_idx:
    k_mod = (k - loop_st_idx) % (loop_fin_idx - loop_st_idx)
    print(path[loop_st_idx + k_mod])
else:
    print(path[k])

Solution (Python):
import collections

N, K = map(int, input().split())
city_list = list(map(int, input().split()))
th_list = []
n = 0
for i in range(N):
    th_list.append(n)
    n = city_list[n] - 1

c = collections.Counter(th_list)
for i in range(N):
    if c[th_list[i]] > 1:
        break
list = [x for x, l in enumerate(th_list) if l == th_list[i]]

if K > N:
    print(th_list[(K - list[0]) % (list[1] - list[0]) + list[0]] + 1)
else:
    print(th_list[K] + 1)

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

when = [-1 for _ in range(N+1)]
new = 1
i = 0

while when[new] == -1:
    when[new] = i
    new = A[new - 1]
    i += 1

line = when[new]
roop = i - when[new]

if K > line:
    K = (K - line) % roop
    for j in range(N+1):
        when[j] -= line
    
for j in range(N+1):
    if when[j] == K:
        print(j)
        break

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

count = [0]*n
roop_st = 0
roop_len = 0
for town in path:
    count[town-1] += 1
    if count[town-1] == 2:
        roop_st = town
        break
roop_st_idx = path.index(roop_st)
roop_fin_idx = path.index(roop_st, roop_st_idx+1)

if k >= roop_st_idx:
    k_mod = (k - roop_st_idx) % (roop_fin_idx - roop_st_idx)
    print(path[roop_st_idx + k_mod])
else:
    print(path[k])

Solution (Python):
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


N, K = MI()
A = LMI()

from math import log2


class Doubling(object):

    def __init__(self, N, K, next0):
        """
        ダブリングのメモ構築 O(NlogK)
        :param N: 解の存在空間の大きさ
        :param K: K個先までのステップを考慮する
        :param next0: i番目の要素の1個先の番号を要素として持つリスト
                      次の要素が存在しない場合には-1を要素として保持する
        """
        next = [[0] * N for _ in range(int(log2(K)) + 1)]
        next[0] = next0
        for k in range(int(log2(K))):
            for i in range(N):
                if next[k][i] == -1:
                    
                    next[k + 1][i] = -1
                else:
                    
                    next[k + 1][i] = next[k][next[k][i]]
        self.next = next

    def query(self, p, K):
        """
        p番目の要素のK個次の要素を求める O(logK)
        """
        for i in reversed(range(int(log2(K)) + 1)):
            if p == -1:
                break
            if (K >> i) & 1:
                p = self.next[i][p]
        return p


d = Doubling(N, K, [a - 1 for a in A])
print(d.query(0, K) + 1)

Solution (Python):
import math



n, k = list(map(int, input().split()))
nums = [-1] + list(map(int, input().split()))
doubling =[[0 for _ in range(n + 1)] for _ in range(62)]

for i in range(62):
	for j in range(1, n + 1):
		if i == 0:
			doubling[i][j] = nums[j]
		else:
			doubling[i][j] = doubling[i - 1][doubling[i - 1][j]]

cur = 1
for i, x in enumerate(bin(k)[2:][::-1]):
	if x == "1":
		cur = doubling[i][cur]
print(cur)

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

history = [-1]*n
ans = []
cur = 0
for i in range(n):
    if history[cur] != -1:
        init_cnt = history[cur]
        loop_cnt = i - history[cur]
        break
    history[cur] = i
    ans.append(cur+1)
    cur = A[cur]

loop = k if k <= init_cnt else init_cnt+((k-init_cnt) % loop_cnt)
print(ans[loop])

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

history = [-1]*n
cur = 0
for i in range(n):
    if history[cur] != -1:
        init_cnt = history[cur]
        loop_cnt = i - history[cur]
        break
    history[cur] = i
    cur = A[cur]

loop = k if k <= init_cnt else init_cnt+((k-init_cnt) % loop_cnt)
print(history.index(loop)+1)

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

pos = 0
visit = [0]*n
move = []
roop = []
while visit[pos] != 2:
    if visit[pos] == 0:
        move.append(pos)
    else:
        roop.append(pos)
    visit[pos] += 1
    pos = a[pos] - 1
if len(move) > k:
    print(move[k]+1)
else:
    print(roop[(k-(len(move)-len(roop))) % len(roop)]+1)

Solution (Python):
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


N, K = MI()
A = LMI()

from math import log2


next = [[0] * N for _ in range(int(log2(K)) + 1)]


next[0] = [a - 1 for a in A]
for k in range(int(log2(K))):
    for i in range(N):
        
        next[k + 1][i] = next[k][next[k][i]]



p = 0
for i in reversed(range(int(log2(K)) + 1)):
    if (K >> i) & 1:
        p = next[i][p]
print(p + 1)

Solution (Python):
'''
Fuad Ashraful Mehmet
University of Asia Pacific,Bangladesh
Date: 7th May 2020
'''

n,k=map(int,input().split())
a=list(map(int,input().split()))
a=[0]+a
vis=[-1]*(n+5)


turn=k
now=1
c=0
while vis[now]==-1:

    if turn<=0:
        print(now)
        exit()
    vis[now]=c
    c+=1
    now=a[now]
    turn=turn-1

diff =c-vis[now]

lo=1
hi=10**25
cost=vis[now]
while lo<=hi:

    mid=(lo+hi)//2
    t=mid*diff
    if t+cost<=k:
       lo=mid+1
    else:
        hi=mid-1

t=hi*diff+cost


rem=k-t

while rem>0:
    now=a[now]
    rem-=1

print(now)

Solution (Python):
n, k = map(int, input().split())
A = list(map(lambda x: int(x)-1, input().split()))
bit = k.bit_length()
table = [[0]*n for _ in range(bit)]
table[0] = A

for i in range(1, bit):
    for j in range(n):
        table[i][j] = table[i-1][table[i-1][j]]

ans = 0
for i in reversed(range(bit)):
    if (1 << i) <= k:
        k -= 1 << i
        ans = table[i][ans]
print(ans+1)

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

A = [int(i) for i in input().split()]


from_ = 1
way = []
way.append(1)
way_set = set([1])

for i in range(K):
    s = A[from_ - 1]
    if(s in way_set):
        way.append(s)
        break
    else:
        way.append(s)
        way_set.add(s)
        from_ = s

key_from = way.index(way[len(way) - 1])
key_to = len(way) - 1



if(K > key_from):
    ans_loop = (K - key_from) % (key_to - key_from)
    ans_num = key_from + ans_loop

    print(way[ans_num])
else:
    print(way[K])

Solution (Python):
n, k = map(int, input().split())
A = list(map(lambda x: int(x)-1, input().split()))
bit = k.bit_length()
table = [[0]*bit for _ in range(n)]
for i in range(n):
    table[i][0] = A[i]

for i in range(1, bit):
    for j in range(n):
        table[j][i] = table[table[j][i-1]][i-1]

ans = 0
for i in reversed(range(bit)):
    if (1 << i) <= k:
        k -= 1 << i
        ans = table[ans][i]
print(ans+1)

Solution (Python):
from collections import defaultdict

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

route = defaultdict(int)
i = 0
loop = []
tail = []

while route[i] < 2:

    if route[i] == 0:
        tail.append(i)
    else:
        loop.append(i)
    
    route[i] += 1
    i = a[i] - 1

if len(tail) > k:
    print(tail[k] + 1)
else:
    temp = len(tail) - len(loop)
    print(loop[(k-temp) % len(loop)] + 1)

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

visited= [1]
ed = set([1])
for i in range(K):
    next_town  = al[visited[i] - 1]
    if next_town in ed:
        loop_sta = visited.index((next_town)) 
        loop_end = len(visited) 
        loop_length = loop_end - loop_sta 
        amari = (K - loop_sta) % loop_length
        ans = visited[loop_sta + amari]
        print(ans)
        exit()
    else:
        visited.append(next_town)
        ed.add(next_town)
        continue

else:
    print(visited[-1])

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

o = [0] * 63

def bi(x):
    i = 0
    while x != 0:
        o[i] = x%2
        x //= 2
        i += 1

bi(K)

n = 0
for i in range(63):
    if o[i]:
        n = A[n]
    A = [A[A[x]] for x in range(N)]
        
print(n+1)

Solution (Python):
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
memo = []
memo_cir = []
visited = [False] * n
index = 0
flag = True
while flag:
    if visited[index]:
        flag = False
    else:
        memo.append(index)
        visited[index] = True
        index = a[index] - 1
flag = False
for i_ in memo:
    if i_ == index:
        flag = True
    if flag:
        memo_cir.append(i_)
if k + 1 >= (len(memo) - len(memo_cir)):
    k -= (len(memo) - len(memo_cir) - 1)
    print(memo_cir[(k % len(memo_cir)) - 1] + 1)
else:
    print(memo[k] + 1)

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

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

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

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

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

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

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

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

Solution (Python):
from collections import defaultdict


def inpl():
    return list(map(int, input().split()))


N, K = inpl()
aa = inpl()

s = 1

route = [s]
ed = set([s])

for i in range(1, K + 1):
    s = aa[s - 1]
    if s in ed:
        Li = route.index(s)
        Ri = len(route)
        idx = Li + (K - Li) % (Ri - Li)
        print(route[idx])
        break
    else:
        route.append(s)
        ed.add(s)
        continue
else:
    print(s)

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

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

def dp(town):
    if visited[town] == 1:
        ans = k%(len(q))
        print(q[ans])
        exit()
    else:
        visited[town] += 1
        q.append(town)

i = 1
next_town = s[1]
while True:
    if i == k:
        print(next_town)
        exit()
    if visited[next_town] == 1:
        break
    else:
        visited[next_town] += 1
        q.append(next_town)
        next_town = s[next_town]
        i += 1
    
index = q.index(next_town)
q = q[index:]
ans = (k-i)%len(q)
print(q[ans])

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

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

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

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

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

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

if k < n:
    print(visited[k])
else:
    first = visited.index(visited[-1])
    loop = visited[::-1][1:].index(visited[-1])+1
    last = (k-first)%loop
    print(visited[first+last])

Solution (Python):
n,k=map(int,input().split())
a=[int(i)-1 for i in input().split()]
p=0
visited=[0]*n
first=[]
roop=[]
while visited[p]!=2:
    if visited[p]==0:
        first.append(p)
    else:
        roop.append(p)
    visited[p]+=1
    p=a[p]
if len(first)>k:
    print(first[k]+1)
else:
    print(roop[(k-(len(first)-len(roop)))%len(roop)]+1)

Solution (Python):
import sys

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

visited = [False] * (N+1)
s = 1

while not visited[s]:
    visited[s] = True
    s = A[s]

a = 1

while a != s:
    K -= 1
    a = A[a]
    if K == 0: 
        print(a)
        sys.exit()

visited = [False] * (N+1)
length = 0
while not visited[s]:
    visited[s] = True
    s = A[s]
    length += 1
    
k = K % length
while k:
    s = A[s]
    k -= 1
    
print(s)

Solution (Python):

import sys
input = sys.stdin.readline
 
n, k = map(int, input().split())
a = [int(item) - 1 for item in input().split()]
visited = [0] * n
 
v = 0
visited[0] = 1
pre = [0]
loop = []
start = False
while True:
    v = a[v]
    if visited[v] == 1:
        start = True
    if visited[v] == 2:
        break
    if not start:
        pre.append(v)
    else:
        loop.append(v)
    visited[v] += 1 
 
if k < len(pre):
    print(pre[k] + 1)
    exit()
k -= len(pre)
print(loop[k % len(loop)] + 1)

Solution (Python):
n,k = (int(x) for x in input().split())
town = [int(i) for i in input().split()]
warp  = [1]
checklist = [0]+[-1]*n
i = 0
j = 1
s = 0
while j<=n:
    warp.append(town[i])
    if checklist[town[i]-1]!=-1:
        s = checklist[town[i]-1]
        loop = warp[s:j]
        break
    checklist[town[i]-1] = j
    i = town[i]-1
    j += 1
if k>=s:
    m = len(loop)
    print(loop[(k-s)%m])
else:
    print(warp[k])

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

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

c = 1
while K:
  if K&1:
    c = A[c]
  na = [0] * (N+1)
  for i in range(N+1):
    na[i] = A[A[i]]
  na,A = A,na
  K >>= 1
print(c)

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

cur = 0
for j in range(59, -1, -1):
	if (k>>j)&1:
		cur = nxt[cur][j]
print(cur+1)