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):




'''

キューに頂点を入れる回数は各々高々１回のみ。
各辺を使う回数は高々一回のみ（辺を戻るような探索は枝切りされている）
結果として、計算量はO(N + M)

'''

from collections import deque
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline



def bfs(conj, start, goal=None, visit=set()):
    visit.add(start)                            
    next_set = deque([(start, 0)])              
                                                
    while next_set:                             
        p, t = next_set.popleft()               
        for q in conj[p]:                       
            if q in visit:                      
                continue
            if q == goal:                       
                return t + 1                    
            visit.add(q)                        
            next_set.append((q, t + 1))         
    return -1


def connection_counter(conj):                   
    cnt = 0
    visit = set()
    for start in range(N):
            if start not in visit:
                cnt += 1
                bfs(start, conj, visit)
    return cnt


def distance_list(conj, start, visit=set()):    
    dist = [0]*N
    visit.add(start)
    next_set = deque([(start, 0)])
    while next_set:
        p, t = next_set.popleft()
        for q in conj[p]:
            if q in visit:
                continue
            dist[q] = t+1
            visit.add(q)
            next_set.append((q, t + 1))
    return dist


def dfs(conj, start, goal=None, visit=set()):
    visit.add(start)                            
    next_set = [(start, 0)]                     
                                                
    while next_set:                             
        p, t = next_set.pop()                   
        for q in conj[p]:                       
            if q in visit:                      
                continue
            if q == goal:                       
                return t + 1                    
            visit.add(q)                        
            next_set.append((q, t + 1))         
    return -1








def dfs2(conj, p=0, goal=None, t=0, past_p=None, visit=set(), second_visit=set()):
    
    visit.add(p)
    for q in conj[p]:
        if q == past_p:
            
            continue
        if q in second_visit:
            
            continue
        if q in visit:
            continue
        if q == goal:
            
            
            continue
        
        
        dfs2(conj, q, goal, t+1, p, visit, second_visit)
    second_visit.add(p)
    
    
    return 


def cycle_detector(conj, p=0, t=0, dictated=False, past_p=None, path=[], visit=set(), second_visit=set(), cycle=[]):
    visit.add(p)
    path.append(p)
    for q in sorted(conj[p]):
        if not dictated:
            if q == past_p:
                continue
        if q in second_visit:
            continue
        if q in visit:
            if not cycle:
                while path:
                    r = path.pop()
                    cycle.append(r)
                    if r == q:
                        break
            continue
        cycle_detector(conj, q, t+1, dictated, p, path, visit, second_visit, cycle)
    second_visit.add(p)
    return cycle


def tree_counter(conj, detail=False):           
    connection_number = 0
    cycle_list = []
    visit = set()
    second_visit = set()
    for start in range(N):
        if start not in visit:
            connection_number += 1
            cycle = cycle_detector(conj, start, visit=visit, second_visit=second_visit, cycle=[])
            if cycle:
                cycle_list.append(cycle)
    if not detail:
        return connection_number - len(cycle_list)
    else:
        return cycle_list


def path_detector(conj, p=0, t=0, past_p=None, full_path=[], visit=set(), second_visit=set(), decrement=False):   
    visit.add(p)
    full_path.append((p + decrement,t))
    for q in sorted(conj[p]):
        if q == past_p:
            continue
        if q in second_visit:
            continue
        if q in visit:
            continue
        path_detector(conj, q, t+1, p, full_path, visit, second_visit, decrement)
    second_visit.add(p)
    full_path.append((p + decrement,t))
    return full_path




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

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


M = N
conj = [set() for _ in range(N)]
for i in range(M):
    u = i
    v = A[i] - 1
    conj[u].add(v)

p = 0
cnt = 0
if K <= N:
    while cnt + 1 <= K:
        p = A[p] - 1
        cnt += 1
    res = p + 1
else:
    cycle = list(
        reversed(cycle_detector(conj, p=0, t=0, dictated=True, past_p=None, path=[], visit=set(), second_visit=set(), cycle=[])))
    len_cycle = len(cycle)

    p = 0
    cnt = 0
    res = 0
    if not len_cycle:
        while cnt < K:
            p = A[p] - 1
            cnt += 1
        res = p + 1
    else:
        while p != cycle[0]:
            p = A[p] - 1
            cnt += 1
        k = (K - cnt) % len_cycle
        res = cycle[k] + 1
print(res)

Solution (Python):
n, k = map(int, input().split())
lst = [0] + list(map(int, input().split()))
dic = {1:0}
loc = 1
for i in range(1, k + 1):
  loc = lst[loc]
  if loc not in dic:
    dic[loc] = i
  else:
    span = i - dic[loc]
    initial = dic[loc]
    z = (k - initial) % span
    for j in range(z):
      loc = lst[loc]
    print(loc)
    exit()
print(loc)

Solution (Python):

N,K = map(int,input().split())
A = [0]+list(map(int,input().split()))
s = {1:0}
l = [1]
i = 1
for j in range(1,10**10):
    i = A[i]
    if i in s:
        sigma = j-s[i]
        break
    s[i] = j
    l.append(i)
if K<s[i]:
    print(l[K])
else:
    K -= s[i]
    mod = l[s[i]:]
    print(mod[K%sigma])

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
s = 1
B = []
set_ = set()
for i in range(N):
    if A[s-1] not in set_:
        set_.add(A[s-1])
        B.append(A[s-1])
        s = A[s-1]
        
    else:
        e = i
        break
idx = B.index(A[s-1])
if K-1<idx: print(B[K-1])
else:
    print(B[idx + (K-idx-1)%(e-idx)])

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

town = 1
once = [0]*(n+1)

for i in range(n):
  if once[town]==0:
    once[town] = 1
  else:
    break
  town = A[town]

rt = A[town]
roop = 1
while rt != town:
  rt = A[rt]
  roop += 1

rt = 1
bf = 0
while rt != town:
  rt = A[rt]
  bf += 1  

if bf<k:
  K = (k-bf)%roop + bf
else:
  K = k

town = 1
for _ in range(K):
  town = A[town]

print(town)

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

num =1
li = [1]
flag = [True]*n
flag[0] = False

for i in range(k):
    num = a[num-1]
    if flag[num-1]:
        li.append(num)
        flag[num-1] = False
    else:
        break

d = li.index(num)
ans = (k-d)%(len(li)-d)+d
print(li[ans])

Solution (Python):
def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    to = [[None]*n for _ in range(60)]
    to[0] = a[:]
    for i in range(1, 60):
        for j in range(n):
            to[i][j] = to[i-1][to[i-1][j]-1]
    p = 1
    for i in range(59, -1, -1):
        num = 1 << i
        if k >= num:
            k -= num
            p = to[i][p-1]
    print(p)
            

if __name__ == "__main__":
    main()

Solution (Python):



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


visit_list = [0] * N
pos = a_list[0]
visit_list[pos-1] = 1
visit_count = 1
remain = K - 1
is_ok = True
ans = 0


while remain>0 and is_ok:
    pos = a_list[pos-1]
    remain -= 1
    visit_count += 1
    if pos==1 or not visit_list[pos-1]==0:
        tmp_1 = visit_count - visit_list[pos-1]
        tmp_2 = remain % tmp_1
        for t in range(tmp_2):
            pos = a_list[pos-1]
        is_ok = False
        break
    else:
        visit_list[pos-1] = visit_count


print(pos)

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

A = [[0 for _ in range(N+1)] for _ in range(100)]
A[0] = [0] + list(map(int, input().split()))

for l in range(1,100):
  
  for j in range(1, N+1):
    
    
    A[l][j] = A[l-1][A[l-1][j]] 
  if 2 ** l > K:
    break

k = K
ans = 1
keta = 0
while k > 0:
  if k & 1:
    ans = A[keta][ans]
  k = k >> 1
  keta += 1

print(ans)

Solution (Python):
N, K = [int(_) for _ in input().split()]
A = [None] + [int(_) for _ in input().split()]
nowkaimin = [None] * (N + 1)
now = 1
kai = 0
nowkaimin[now] = kai
while True:
    now = A[now]
    kai += 1
    if kai == K:
        print(now)
        exit()
    if nowkaimin[now] is not None:
        break
    nowkaimin[now] = kai


R = (K - nowkaimin[now]) % (kai - nowkaimin[now])
for i, v in enumerate(nowkaimin):
    if v == nowkaimin[now] + R:
        print(i)
        exit()

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

X = 0
town = 1
counted = [0 for _ in range(N)]
List = [0 for _ in range(N)]
for k in range(N):
  X += 1
  counted[k] = town
  town = A[town-1]
  if List[town-1] == 1:
    ini = counted.index(town)
    Q = X - ini
    break
  else:
    List[town-1] = 1
if K >= ini:    
  num = (K-ini) % Q
  print(counted[ini+num])
else:
  print(counted[K])

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

for i in range(k):
    now = a[now-1]
    
    
    
    if alr[now-1] != 0:
        now = path[path.index(now) + (k-i-1)%(len(path) - path.index(now))]
        break
    path.append(now)
    alr[now-1] += 1

print(now)

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[0]*n
info=[1]
now=1
while town[now-1]==0:
    town[now-1]+=1
    now=a[now-1]
    info.append(now)
loop_list=list(info[info.index(now):-1])
loop_len=len(loop_list)
before_loop_list=list(info[:info.index(now)])


if k<len(before_loop_list):
    print(before_loop_list[k])
else:
    print(loop_list[((k-len(before_loop_list))%loop_len)])

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

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

judge = N*[0]
pos = 0
freq = 0

while judge[pos]==0 and K > 0:
	judge[pos] = 1
	pos = A[pos]
	K -= 1
	freq+=1

tmp = pos
pos = 0
while pos!=tmp:
	pos = A[pos]
	freq -= 1


if K==0:
	print(pos+1)
else:
	K %= freq
	pos = tmp
	for i in range(K):
		pos = A[pos]
	print(pos+1)

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

(n, k), s = map(int, input().split()), list(map(int, input().split()))
x, c = [1, s[0]], 0
for i in range(n): x.append(s[x[-1] - 1])
if len(x) > k: print(x[k]); exit()
while x[c] != s[x[-1] - 1]: c += 1
print(x[((k - c) % (len(x) - c)) + c])

Solution (Python):
import sys
def Ii():return int(sys.stdin.buffer.read())
def Mi():return map(int,sys.stdin.buffer.readline().split())
def Li():return list(map(int,sys.stdin.buffer.readline().split()))

n,k = Mi()
a = Li()
b = [1]
b.append(a[0])
flag = False
for i in range(n):b.append(a[b[-1]-1])
if len(b) > k:
  print(b[k])
  exit(0)
for j in range(len(b)):
  if b[j] == a[b[-1]-1]:
    break
    
roop = len(b)-j
roopk = (k-j)%roop
print(b[roopk+j])

Solution (Python):


import sys
stdin = sys.stdin

def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))

def main():
    n, k = na()
    a = na()
    visited_time = [-1] * n
    visited_time[0] = 0
    x, t = 0, 0
    while True:
        x = a[x] - 1
        t += 1
        if visited_time[x] > 0:
            b = visited_time[x]
            r = t - visited_time[x]
            break
        else:
            visited_time[x] = t
    if k <= b:
        print(visited_time.index(k) + 1)
    else:
        c = (k-b) % r
        print(visited_time.index(b+c) + 1)

if __name__ == "__main__":
    main()

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[0]*n
info=[1]
now=1
while town[now-1]==0:
    town[now-1]+=1
    now=a[now-1]
    info.append(now)
loop_list=list(info[info.index(now):-1])
loop_len=len(loop_list)
before_loop_list=list(info[:info.index(now)])
if k<len(before_loop_list):
    print(before_loop_list[k])
else:
    print(loop_list[((k-len(before_loop_list))%loop_len)])

Solution (Python):
n,k = (int(a) for a in input().split())
A =  [-1] + list(map(int,input().split()))
t = [1]
flag =[0,1] + [0]*(n-1)
x = A[1]
while flag[x] == 0 :
    t.append(x)
    flag[x] = 1
    x = A[x] 

if k <= len(t) -1 :
    print(t[k])
else :
    l = t[t.index(x):]
    k = k - (len(t) - 1)
    k %= len(l)
    print(l[k-1])

Solution (Python):
N, K = map(int, input().split())
G = [[] for _ in range(N)]
for i, a in enumerate(map(int, input().split())):
    G[i] = a - 1
now = 0
seen = set()

for i in range(1, K+1):
    seen.add(now)
    now = G[now]
    if now in seen:
        break
K -= i
if K > 0:
    
    seen = set()
    for j in range(1,K+1):
        seen.add(now)
        now = G[now]
        if now in seen:
            break
    
    r = K % j
    for _ in range(r):
        now = G[now]
print(now + 1)

Solution (Python):
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
N,K=MI()
A=[0]+LI()
c=1
turn=[-1]*(N+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):
import sys

def main():
    n, k = map(int, sys.stdin.buffer.readline().split())
    a = [0] + list(map(int, sys.stdin.buffer.readline().split()))

    visited = [0]*(n+1)
    town = 1
    for i in range(1, k+1):
        town = a[town]
        if visited[town] == 0:
            visited[town] = i
        else:
            cyc = (k - visited[town])%(i - visited[town]) + visited[town]
            print(visited.index(cyc))
            exit()
    print(town)

if __name__ == "__main__":
    main()

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):
import sys

N, K = map(int, input().split())
A = list(map(int, input().split()))
d = {1: 0}
pre = 1
for i in range(1, N+1):
    new = A[pre-1]
    if d.get(new):
        roop_start = d[new]
        roop_end = i
        roop_pos = new
        break
    if i==K:
        print(new)
        sys.exit()
    d[new] = i
    pre = new

K -= roop_start
K %= roop_end-roop_start
pre = roop_pos
for i in range(K):
    pre = A[pre-1]
print(pre)

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

before=k
roop=1
cnt={}
nxt=1
mp = [1]
for i in range(1, k+1):
    if nxt not in cnt:
        cnt[nxt] = i
        nxt = a[nxt]
    else:
        roop = i - cnt[nxt]
        before = cnt[nxt]-1
        break
    mp.append(nxt)
print(mp[before + (k-before)%roop])

Solution (Python):
import sys

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

for i in range(1, K+1):
    town = A[town]
    if visited[town] == 0:
        visited[town] = i
    else:
        loop = i - visited[town]
        place = (K - visited[town]) % loop + visited[town]
        print(visited.index(place))
        sys.exit()
print(town)

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



A = [A[k]-1 for k in range(N[0])]

L = [0]*N[0]
p = 0
t = 0
L[0] = 1
for k in range(N[1]):
    if L[A[p]] == 0:
        L[A[p]] = k+2
        p = A[p]
    else:
        t = 1
        break

if t == 0:
    print(p+1)
else:
    loop = L[p]-L[A[p]]+1
    stop = (N[1]-L[p]+1) % loop

    for k in range(stop):
        p = A[p]
    print(p+1)

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

def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
from math import ceil, floor, log2





class Doubling:
    def __init__(self, lst, max_step):
        self.lst = lst
        self.max_step = max_step
        self.k = int(log2(max_step * 2 - 1)) + 1
        
        self.D = self.create()

    def create(self):
        len_ = len(self.lst)
        D = [[-1] * len_ for _ in range(self.k)]
        D[0] = self.lst
        d = 2
        for i in range(1, self.k):
            for j in range(len_):
                D[i][j] = D[i - 1][D[i - 1][j]]
            d *= 2
        
        return D

    def step(self, start, step):
        v = start
        for i in range(self.k, -1, -1):
            l = 1 << i
            if l <= step:
                v = self.D[i][v]
                
                step -= l
        return v

def solve():
    N, K = MI()
    A = LI1()

    db = Doubling(A, K)
    v = db.step(0, K)
    print(v+1)

if __name__ == '__main__':
    solve()

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

def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
from math import ceil, floor, log2






def solve():
    N, K = MI()
    

    D = [[0] * N for _ in range(int(log2(K))+1)]
    D[0] = LI1()
    
    for i in range(1, int(log2(K))+1):
        for j in range(N):
            tmp = D[i-1][j]
            D[i][j] = D[i-1][tmp]
    
    
    v = 0
    while K > 0:
        tmp = int(log2(K))
        K = K - 2 ** tmp
        v = D[tmp][v]
        
    print(v+1)

if __name__ == '__main__':
    solve()

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

rireki = [0] * (2 * 10 ** 5 + 1)
flag = [[] for _ in range(2 * 10 ** 5 + 1)]
rireki[0] = 1
flag[1].append(0)
count = 0
roop_start = 0
roop_count = 0
while True:
    count += 1
    rireki[count] = a[rireki[count - 1] - 1]
    flag[rireki[count]].append(count)
    if len(flag[rireki[count]]) == 2:
        roop_start = flag[rireki[count]][0]
        roop_count = flag[rireki[count]][1] - flag[rireki[count]][0]
        break
    if count == K:
        break
if roop_count != 0:
    print(rireki[(K - roop_start) % roop_count + roop_start])
else:
    print(rireki[K])

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

field = [(i, j) for i, j in zip(range(n), list(map(int, input().split())))]


town = 0 
order = 0 
visited = {town: order} 

while True:
    trans = field[town][1] - 1 
    n_town = field[trans][0] 
    if n_town not in visited.keys():
        order += 1
        visited[n_town] = order  
    else: 
        st_circ = visited[n_town]
        break
    town = n_town



vk = list(visited.keys())
mae = len(vk[:st_circ])
circ = len(vk[st_circ:])

if k < mae:
    ans = vk[k]
else:
    idx = (k - mae) % circ
    ans = vk[idx + mae]

print(ans+1)

Solution (Python):
N,K=map(int,input().split())
A=[int(x)-1 for x in input().split()]
B=[0]
visited=[False]*N
for g,here in enumerate(B):
	if visited[here]:
		break
	visited[here]=True
	B.append(A[here])
s=B.index(here)
r=(K-s)%(g-s)
ans=B[s:][r]+1 if K>=s else B[K]+1
print(ans)

Solution (Python):




def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    A = [0] +A  
    visited = [0] * (N+1)
    town = 1
    cycle = 0
    for i in range(1,K+1):
        town = A[town]
        if visited[town] ==0:
            visited[town] = i
        else:
            cycle = i - visited[town]
            place = (K - visited[town]) % cycle + visited[town]
            print(visited.index(place))
            exit()
    print(town)




if __name__ == "__main__":
    main()

Solution (Python):
import sys
import numpy as np
from collections import defaultdict





def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    A = [0] +A  
    visited = [0] * (N+1)
    town = 1
    cycle = 0
    for i in range(1,K+1):
        town = A[town]
        if visited[town] ==0:
            visited[town] = i
        else:
            cycle = i - visited[town]
            place = (K - visited[town]) % cycle + visited[town]
            print(visited.index(place))
            exit()
    print(town)




if __name__ == "__main__":
    main()

Solution (Python):
import sys
import numpy as np
from collections import defaultdict





def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    A = [0] +A  
    visited = [0] * (N+1)
    town = 1
    cycle = 0
    for i in range(1,K+1):
        town = A[town]
        if visited[town] ==0:
            visited[town] = i
        else:
            cycle = i - visited[town]
            place = (K - visited[town]) % cycle + visited[town]
            for j in range(N+1):
                if visited[j] == place:
                    print(j)
                    exit()
    print(town)




if __name__ == "__main__":
    main()

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

    tele_num = 0
    check = [0]*(N+1)
    check[1] = 1
    temp = 1
    i = 2
    roop_num = 0
    sho = 0
    amari = 0

    while i != K+2:
        temp1 = A[temp-1]
        if check[temp1] != 0:
            roop_num = check[temp] - check[temp1] + 1
            tele_num = K + 2 - i - 1
            sho = tele_num // roop_num
            amari = tele_num % roop_num
            break

        check[temp1] = i
        i += 1
        temp = temp1

    

    j = 0
    temp = temp1
    while j != amari:
        temp1 = A[temp-1]
        
        j += 1
        temp = temp1

    print(temp)
    

main()

Solution (Python):
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
    return int(input())

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


def solve():
    n, k = rl()
    A = rl()
    
    
    
        
        
    curr = 1
    seen = {1:0}

    for i in range(1, k + 1):
        curr = A[curr - 1]
        if i == k:
            print (curr)
            return
        elif curr in seen:
            break
        seen[curr] = i

    cycle_len = i - seen[curr]
    

    while 1:
        if i % cycle_len == k % cycle_len:
            print (curr)
            return
        i += 1
        curr = A[curr - 1]






mode = 's'

if mode == 'T':
    t = ri()
    for i in range(t):
        solve()
else:
    solve()

Solution (Python):
from collections import deque

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

tere = {}
for i in range(n):
    tere[i+1] = a[i]

mati = deque([1])
mark = set([1])
tugi = 1
for i in range(1, k+1):
    if tere[tugi] not in mark:
        mati.append(tere[tugi])
        mark.add(tere[tugi])
    else:
        mati.append(tere[tugi])
        mark.add(tere[tugi])
        break
    tugi = tere[tugi]
else:
    print(tugi)
    exit()

mati = list(mati)
cnta = len(mati)-1
i = mati.index(mati[-1]) + 1
cntroop = cnta - i + 1
roop = mati[i:]

print(roop[(k-cnta)%cntroop-1])

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = [-1]*n
s = []
v = 0

while b[v] == -1:
    b[v] = len(s)
    s.append(v)
    v = a[v]-1
    
c = len(s) - b[v]
l = b[v]

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

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

r = []
f = [-1]*N
now = 0
loop = 0

i = 0


while i < K:
    r.append(now)
    f[now] = i
    now = A[now]
    i += 1
    if f[now] >= 0:
        loop = i-f[now]
        nokori = K-i
        print(r[f[now]+nokori%loop]+1)
        break
else:
    print(now+1)

Solution (Python):
import sys
import itertools

n, k = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
a_len = len(a) - 1

b = [1]
labeled = set(b)
index = 1
loop_start = 0
while len(labeled) <= a_len:
  p = a[index - 1]
  if p in labeled:
    loop_start = b.index(p)
    break
  labeled.add(p)
  b.append(p)
  index = p



loop_len = len(b) - loop_start


if k < len(b) - 1:
  print(b[k])
else:
  kk = k - loop_start
  
  kk %= loop_len
  
  kk += loop_start
  

  print(b[kk])

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

t_zero = [-1] * N

t = 0
a = 1

while t_zero[a-1] == -1:
  if t == K:
    break
  t_zero[a-1] = t
  t += 1
  a = A[a-1]
  
else:
  k = (K - t_zero[a-1]) % (t - t_zero[a-1])
  a = a = t_zero.index(t_zero[a-1] + k) + 1
print(a)

Solution (Python):
import numpy as np
def resolve():
    N,K = map(int,input().split())
    A = list(input().split())
    current_p = 0
    loop_length = 0
    loop_start = 0
    Nlist = - np.ones(N, dtype = int)
    Nlist[0] = 0
    for i in range(1, min(N + 1,K + 1)):
        next_p = int(A[current_p]) - 1
        if Nlist[next_p] == -1:
            current_p = next_p
            Nlist[next_p] = i
        else:
            loop_start = Nlist[next_p]
            loop_length = i - loop_start
            break
    if loop_length != 0:
        ans =  loop_start + (K - loop_start) % loop_length
    else:
        ans = K 
    print(np.where(Nlist == ans)[0][0] + 1)
resolve()

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

seen = [False] * (n+1)
visited = []
nxt = 1
cnt = 0
while not seen[nxt] and cnt != k:
    seen[nxt] = True
    visited.append(nxt)
    nxt = a[nxt]
    cnt += 1

if cnt == k:
    print(nxt)
    exit()
    
idx = visited.index(nxt)
print(visited[idx:][(k-idx)%(len(visited)-idx)])

Solution (Python):
'''
path = 'sub1_51.txt'
f=open(path)
data1 = f.read()
f.close()
N=data1.split()
'''
n,k=map(int,input().split())
A=list(map(int,input().split()))
'''
n=int(N[0])
k=int(N[1])
A=N[2:]
'''
A=[int(i)-1 for i in A]
B=[]
cnt=[0]*n
m=0
for i in range(2*10**5):
    B.append(m)
    cnt[m]+=1
    if cnt[m]>1:
        break
    m=A[m]
c=len(B)-(B.index(m)+1)
print(1+B[(max(k-B.index(m),0))%c + min(B.index(m),k)])

Solution (Python):
n, k = map(int, input().split())
A = [int(x) - 1 for x in input().split()]

B = [0]
visited = [False] * n
for i, b in enumerate(B):
    if visited[b]:
        break
    visited[b] = True
    B.append(A[b])

j = B.index(b)
r = (k - j) % (i - j)
ans = B[j:][r] + 1 if k >= j else B[k] + 1

print(ans)

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

p = 0
t = 0
while True:
    ts[p].append(t)
    if t == k:
        print(p + 1)
        exit()
    if len(ts[p]) == 2:
        if (k - ts[p][0]) % (ts[p][1] - ts[p][0]) == 0:
            print(p + 1)
            exit()
    p = a[p]
    t += 1

Solution (Python):
import sys
import time

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

queue = {}

start = -1
count = 1

now_town = 1

for i in range(K):
    if town_list[now_town - 1] in queue:
        start = town_list[now_town - 1]
        break
    queue[town_list[now_town - 1]] = count
    now_town = town_list[now_town - 1]
    count += 1

if start == -1:
    print(now_town)
    sys.exit()

roop = len(queue) - (queue[start] - 1)
before_len = queue[start]

print(list(queue.keys())[(K - before_len) % roop + before_len - 1])

Solution (Python):
import sys
import numpy as np


def solve(N, K, xs):
    "void()"
    town_to_time = np.zeros(N, np.uint32)
    time_to_town = np.zeros(N, np.uint32)
    cur = 1
    for i in range(K):
        cur = xs[cur - 1]
        
        if town_to_time[cur - 1]:
            
            period = i + 1 - town_to_time[cur - 1]
            rest = K - i - 1
            rest %= period
            
            print(time_to_town[town_to_time[cur - 1] + rest - 1])
            return

        town_to_time[cur - 1] = i + 1
        time_to_town[i] = cur
    print(cur)


IN1 = """
4 5
3 2 4 1
"""

IN2 = """
6 727202214173249351
6 5 2 5 3 2
"""

IN3 = """
6 100
2 3 4 5 6 1
"""


def main():
    """
    >>> as_input(IN1)
    >>> main()
    4
    >>> as_input(IN2)
    >>> main()
    2
    >>> as_input(IN3)
    >>> main()
    5
    """
    N, K = map(int, input().split())
    xs = np.array(list(map(int, input().split())))
    solve(N, K, xs)


def _test():
    import doctest
    as_input(IN1)
    main()
    doctest.testmod()


def as_input(s):
    "use in test, use given string as input file"
    import io
    global read, input
    f = io.StringIO(s.strip())
    input = f.readline
    read = f.read


USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":
        
        
        from my_module import solve  
    elif sys.argv[-1] == "-t":
        _test()
        sys.exit()
    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:
        
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read

    main()

Solution (Python):
N,K = map(int,input().split())
A = [0]+list(map(int,input().split()))
dp = [False]*(N+1)
tele = 0
for i in range(10**6):
    if i==0:
        tele = 1
        dp[tele]=True
    else:
        tele = A[tele]
        if dp[tele]==True:
            finish = i
            tele1 = tele
            break
        else:
            dp[tele]=True


tele = 0
for i in range(10**6):
    if i == 0:
        tele = 1
        if tele == tele1:
            start = i
            break
    else:
        tele = A[tele]
        if tele == tele1:
            start = i
            break

loop = finish-start
if K<=start:
    ans = 1
    for i in range(K):
        ans = A[ans]
    print(ans)
else:
    ans = 1
    for i in range(start+(K-start)%loop):
        ans = A[ans]
    print(ans)