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 bisect
import sys
import math
from collections import deque
from heapq import heappush, heappop

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29

DIV = (10**9) + 7


def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    N, K = isRaw()
    As = isRaw()
    ts = [0]*N
    now = 0
    lstart = 0
    lsize = 0
    d = {}
    for i in range(N):
        ts[i]=now
        d[now]=i
        now = As[now]-1
        if now in d:
            lstart=d[now]
            lsize=i-d[now]+1
            break
    if K < lstart:
        return ts[K]+1
    return ts[((K-lstart) % lsize)+lstart]+1

print(main())

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

n=[1]
t=1
ord=[-1]*(N+1)
ord[0]=0

while True:
    t=A[t-1]
    if ord[t] != -1:
        f=n.index(t)
        break
    n.append(t)
    ord[t]=0

k=len(n)-f

if K>=f:
    print(n[f+(K-f)%k])

else:
    print(n[K])

Solution (Python):


import sys
import math
import collections
import itertools
import bisect
INF = 10 ** 13
MOD = 10 ** 9 + 7
def input() : return sys.stdin.readline().strip()
def gcd(x, y) : return x if y == 0 else gcd(y, x%y)
def lcm(x, y) : return (x * y) // gcd(x, y)
def I() : return int(input())
def LI() : return [int(x) for x in input().split()]
def RI(N) : return [int(input()) for _ in range(N)]
def LRI(N) : return [[int(x) for x in input().split()] for _ in range(N)]
def LS() : return input().split()
def RS(N) : return [input() for _ in range(N)]
def LRS(N) : return [input().split() for _ in range(N)]
def PL(L) : print(*L, sep="\n")
def YesNo(B) : print("Yes" if B else "No")
def YESNO(B) : print("YES" if B else "NO")

N, K = LI()
A = LI()

D = 60
to = [[-1] * N for _ in range(D)]
to[0] = [a-1 for a in A]

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

now = 0
time = 0
while K > 0:
    if K&1:
        now = to[time][now]
    
    K >>= 1
    time += 1

print(now+1)

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

while 1:
    cnt+=1
    pl=a[pl-1]
    
    
    if visit[pl-1]!=-1:
        loop=visit[pl-1]
        
        break
    visit[pl-1]=cnt
    if cnt==k:
        print(pl)
        exit()

loop_len=cnt-loop

k=(k-loop)%loop_len+loop
print(visit.index(k)+1)

Solution (Python):
n, k = map(int, input().split())
A = list(map(int, input().split()))
s = []
order = [-1] * (n+1)
l = 1
while order[l] == -1:
    order[l] = len(s)
    s.append(l)
    l = A[l-1]
new = s[order[l]:]
t = len(new)
first = len(s) - t
if k > first:
    print(new[(k-first)%t])
else:
    print(s[k])

Solution (Python):

import sys
from collections import defaultdict
N,K=map(int, sys.stdin.readline().split())
A=[None]+map(int, sys.stdin.readline().split())

L={}        
visit=defaultdict(lambda: 0)    
x=1         
cnt=0       
while visit[x]<=2: 
    if visit[x]==2:
        L[cnt]=x
    if cnt==K:  
        print x 
        quit()
    visit[x]+=1  
    x=A[x]      
    cnt+=1

len_L=len(L)

LL={}
for cnt,city_num in L.items():
    LL[cnt%len_L]=city_num

print LL[K%len_L]

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

now = 1
loop_node = []
first_loop = 0
l = [0 for _ in range(N)]
while True:
    l[now - 1] += 1
    if l[now - 1] == 3:
        break

    if l[now - 1] == 2:
        loop_node.append(now)

    now = A[now - 1]
    first_loop += 1

loop_num = len(loop_node)
first_loop -= loop_num * 2

if K < first_loop:
    now = 1
    for _ in range(K):
        now = A[now - 1]
    print(now)
else:
    print(loop_node[(K - first_loop) % loop_num])

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

now = 0
while k > 0:
    if k & 1:
        now = a[now]

    a_next = [-1] * n
    for i in range(n):
        a_next[i] = a[a[i]]

    a = copy.copy(a_next)
    k = k >> 1

ans = now + 1
print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


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

    tree = [[] for _ in range(n)]
    for idx, a in enumerate(A):
        tree[idx].append(a - 1)

    def dfs(pre, dist):
        depth[pre] = dist
        for to in tree[pre]:
            if depth[to] != f_inf:
                cycle.append([depth[to], depth[pre] + 1])
                return
            else:
                dfs(to, dist + 1)

    cycle = []
    depth = [f_inf for _ in range(n)]
    dfs(0, 0)

    cycle_start = cycle[0][0]
    cycle_end = cycle[0][1]
    if k <= cycle_start:
        print(depth.index(k) + 1)
    else:
        remainder = (k - cycle_start) % (cycle_end - cycle_start)
        res = cycle_start + remainder
        print(depth.index(res) + 1)


if __name__ == '__main__':
    resolve()

Solution (Python):
from sys import stdin

def main():
    n, k = map(int, stdin.readline().rstrip().split())
    a = [int(x)-1 for x in stdin.readline().rstrip().split()]
    n = a[0]
    his = [-1, n]
    f = his.append
    s = set()
    while True:
        n = a[n]
        if n in s:
            f(n)
            break
        f(n)
        s.add(n)
    idx = his.index(his[-1])
    loop = len(his[his.index(his[-1]):-1])
    if len(his) > k:
        print(his[k]+1)
    else:
        t = (k - idx) % loop
        g = his[idx:-1]
        print(g[t]+1)
main()

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


i = 1
to = [[a for a in A]]
while pow(2, i) < K:
    t = [to[i-1][to[i-1][j]] for j in range(N)]
    to.append(t)
    i += 1

ans = 0
for j in range(i):
    if K & (1 << j) > 0:
        ans = to[j][ans]
print(ans+1)

Solution (Python):
n,k = map(int,input().split())
an = list(map(int, input().split()))
copyan = an[:]
i = copyan[0]
copyan[0]=10**6
movecount = 1

if i != 1:
    while True:
        memo = i
        if k == movecount:
            print(i)
            
            exit()
        i = copyan[i-1]
        
        if i >=300000:
            yokei = i%(10**6)         
            break
        copyan[memo-1]=10**6 + movecount
        movecount += 1
        
else:
    print(1)
    exit()
roopnum = movecount - yokei
x = (k-yokei)%roopnum

ans = copyan.index(10**6+yokei+x) +1
print(ans)

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


i = 1
to = [[a for a in A]]
while pow(2, i) < K:
    t = [to[i-1][to[i-1][j]] for j in range(N)]
    to.append(t)
    i += 1

i -= 1
ans = 0
while i >= 0:
    if K & (1 << i) > 0:
        ans = to[i][ans]
    i -= 1
print(ans+1)

Solution (Python):
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N,K = map(int, readline().split())
A = np.int32(read().split())

A -= 1

def mult(A,B):
    return B[A]

def power(A,n):
    if not n:
        return np.arange(N)
    B = power(A,n//2)
    B = mult(B,B)
    return mult(A,B) if n & 1 else B

print(power(A, K)[0] + 1)

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 
    for _ in range(l):
        p = a[p]
        i +=1

    print(p+1)

Solution (Python):
n, k = map(int,input().split())
a = [int(i) for i in input().split()]
s = []
ord = [-1] * (n+1)
c, l = 1, 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]
print(s[k] if (k < l) else s[l + (k - l) % c])

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


i = 1
to = [[a for a in A]]
while pow(2, i) < K:
    t = [to[i-1][to[i-1][j]] for j in range(N)]
    to.append(t)
    i += 1

i -= 1
ans = [i for i in range(N)]
while i >= 0:
    if K & (1 << i) > 0:
        for j in range(N):
            ans[j] = to[i][ans[j]]
    i -= 1
print(ans[0]+1)

Solution (Python):

n,k=map(int,input().split())
a=list(map(int, input().split()))
b=[1]
ba={1}
c=0
m=0

for i in range(n):
    if a[m] not in ba:
        b.append(a[m])
        ba.add(a[m])
        c+=1
        m=a[m]-1
    else:
        e=a[m]
        break

e=b.index(e)

bc=b
b=b[e:c+1]
f=c+1-e
if c>k:
    if c-1>=k:

        print(bc[k])
        exit()
if 1 not in b:
    
    ans=(k-e)%f
    print(b[ans])
else:

    ans=k%f
    print(b[ans])

Solution (Python):
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = [i-1 for i in a]
visited = [-1]*n
route = []
now = 0
hop = 0
while visited[now] == -1:
    visited[now]=hop
    route.append(now)
    now = a[now]
    hop+=1
loop_st = 0
for r in route:
    if r==now: break
    loop_st+=1
loop = route[loop_st:]
if k < len(route):
    print(route[k]+1)
else:
    print(loop[(k-loop_st)%len(loop)]+1)

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

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


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

    tree = [[] for _ in range(n)]
    for idx, a in enumerate(A):
        tree[idx].append(a - 1)

    start = []
    depth = [0 for _ in range(n)]

    def dfs(v, p, d, cnt):
        depth[v] = d
        for u in tree[v]:
            if visited[u]:
                start.append([u + 1, depth[u], cnt + 1])
                return
            else:
                visited[u] = True
                dfs(u, v, d + 1, cnt + 1)
        return

    visited = [False for _ in range(n)]
    visited[0] = True
    dfs(0, -1, 0, 0)

    if k <= start[0][1]:
        print(depth.index(k) + 1)
    else:
        cnt = (k - start[0][1]) % (start[0][2] - start[0][1])
        res = start[0][1] + cnt
        print(depth.index(res) + 1)


if __name__ == '__main__':
    resolve()

Solution (Python):
n, k = map(int, input().split())
A = [int(a) for a in input().split()]
Jump = [None] * n
Jump[0] = 1
Rireki = [-1] * (n+1)
Rireki[0] = 0
next = 0
for i in range(1,n+1):
    to = A[next]

    if Rireki[to] >= 0:
        start = Jump.index(to)
        end = i
        dis = end - start

        roop = (k-start) % dis
        print(Jump[start+roop])
        break
    Rireki[to] = i
    Jump[i] = to
    next = to-1
    if i ==k:
        print(to)
        break

Solution (Python):
n, k = map(int, input().split())
a = [int(i) - 1 for i in input().split()]
ans = 0
while k:
    if k & 1:
        ans = a[ans]
    c = [a[a[i]] for i in range(n)]
    a = c[:]
    k >>= 1
print(ans + 1)

Solution (Python):
n,k = map(int,input().split())
a = [int(i)-1 for i in input().split()]
seen = []
cnt = [-1]*n
now = 0
while cnt[now] == -1:
    cnt[now] = len(seen)
    seen.append(now)
    now = a[now]
loop = len(seen)-cnt[now]
toloop = cnt[now]
if k <= toloop:
    ans = seen[k] + 1
else:
    k = (k-toloop)%loop
    ans = seen[toloop+k] + 1
print(ans)

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

r = [0]*N

now = 0
r[now]=1
for i in range(N):
  now = A[now]-1
  if r[now] == 0:
    r[now] = i+2
  else:
    x1 = r[now]
    x2 = i+1
    break

roop_num = x2 - x1 + 1
x = (K-x1+1) % roop_num

if K < x1:
  print(r.index(K+1)+1)
else:
  print(r.index(x1 + x)+1)

Solution (Python):

n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
nxt = 1
loop = []
tset = set()
final = -1
while 1:
    loop.append(nxt)
    tset.add(nxt)
    nxt = a[nxt-1]
    if nxt in tset:
        final = nxt 
        break
m = -1
for i in range(len(loop)):
    if loop[i]==final:
        m = i
        break
l = len(loop)
if k < m:
    print(loop[k])
else:
    print(loop[(k-m)%(l-m)+m])

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

visit=set()
order=[-1]*(N+1)
p=1
cnt=0

while not (p in visit):
    visit.add(p)
    order[cnt]=p
    p=A[p]
    cnt+=1

start=order.index(p)
end=cnt
if K>end:
    K-=(end-start)*max(0,(K-start)//(end-start)-1)
p=1
while K>0:
    p=A[p]     
    K-=1

print(p)

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



now = 0
past = []
past_set = set()

for i in range(N):
    if now in past_set:
        break
    past.append(now)
    past_set.add(now)
    now = A[now]


i_loop = past.index(now)
loop = past[i_loop:]
if K >= i_loop:
    print(loop[(K-i_loop) % len(loop)] +1)
else:
    print(past[K] +1)

Solution (Python):
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def doubling(MAX, A):
    """ ダブリング """

    N = len(A)
    nxt = list2d(MAX, N, -1)
    for i, a in enumerate(A):
        nxt[0][i] = a
    for k in range(1, MAX):
        for i in range(N):
            nxt[k][i] = nxt[k-1][nxt[k-1][i]]
    return nxt

N, K = MAP()
A = [a-1 for a in LIST()]
MAX = 64

nxt = doubling(MAX, A)

ans = 0
for k in range(MAX-1, -1, -1):
    if K >> k & 1:
        ans = nxt[k][ans]
print(ans+1)

Solution (Python):
from sys import stdin
import math
import fractions
from collections import deque
from collections import Counter
import itertools

INF = 10 ** 10

N, K  = [int(x) for x in stdin.readline().rstrip().split()]
A = [0] + [int(x) for x in stdin.readline().rstrip().split()]

stack = [1]
nextt = A[1]
visited_dict = {1: True}

while True:
    if not visited_dict.get(nextt, False):
        stack.append(nextt)
        visited_dict[nextt] = True
    else:
        stack.append(nextt)
        break
    nextt = A[nextt]

    if len(stack) > K:
        print(stack[K])
        exit()

num1 = stack.pop()
length = len(stack)
tmp = []
while True:
    num2 = stack.pop()
    if num1 != num2:
        tmp.append(num2)
    else:
        tmp.append(num2)
        break

tmp = tmp[::-1]

index = (K - length) % len(tmp)

print(tmp[index])

Solution (Python):
from collections import defaultdict

n, k = map(int, input().split())
*a, = map(int, input().split())
a = [a[i] - 1 for i in range(n)]
ans = 0

if k <= n:
    i = 0
    while(k > 0):
        ans = a[i]
        i = a[i]
        k -= 1
    ans += 1

else:
    
    start_period = 1
    period_i = -1
    
    d = defaultdict(int)
    d[0] = 1
    i = 0
    count = 1
    while(1):
        if a[i] in d.keys():
            period_i = count
            start_period = d[a[i]]
            break

        d[a[i]] = count + 1
        i = a[i]
        count += 1
        
    
    d_r = {i:k for k, i in d.items()}

    ans = d_r[start_period + ((k - (start_period - 1)) % (period_i - start_period + 1))] + 1
    
    
print(ans)

Solution (Python):
mNK = map(int, input().split())
lNK = list(mNK)

mTel = map(int, input().split())
lTel = list(mTel)

lWent = [-1 for i in range(lNK[0])]
nTown = 0
loopCnt = -1

for i in range(lNK[1]):
    nextTown = lTel[nTown] - 1
    lWent[nTown] = i
    if(lWent[nextTown] != -1):
        loopCnt = i - lWent[nextTown] + 1
        surplus = (lNK[1] - i - 1) % loopCnt
        nTown = lWent.index(lWent[nextTown] + surplus)
        break
    nTown = nextTown

print(nTown + 1)

Solution (Python):




import sys
input = sys.stdin.readline




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

    s = []
    ord = [-1] * (N+1)
    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:
        res = s[K]
    else:
        K -= l
        K %= c
        res = s[l+K]

    print(res)



main()

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

now=1
to=0
t=k
l=[0]*n
l[0]=1
cnt=2

while t>0:
    to=a[now-1]
    t-=1
    if l[to-1]!=0:
        now=to
        break
    else:
        l[to-1]=cnt
        cnt+=1
    now=to

if t==0:
    print(now)
else:
    loop=max(l)-l[to-1]+1 
    start=l[to-1]-1 
    ans=l.index((k-start)%loop+start+1)+1
    print(ans)

Solution (Python):
def solve(N, K, A):
    idx = [-1 for _ in range(len(A))]
    now = 0
    period = 0
    bias = 0
    tmp = []
    found = False
    i = 0
    while not found:
        tmp.append(now+1)
        if idx[now] == -1:
            idx[now] = i
        else:
            period = i - idx[now]
            cycle = tmp[-period-1:-1]
            bias = i - period
            break
        now = A[now]-1
        i += 1

    if K <= bias:
        now = 0
        for _ in range(K):
            now = A[now] - 1
        print(now + 1)
    else:
        K -= bias
        K = K % period
        print(cycle[K])

if __name__=="__main__":
    N,K = [int(a) for a in input().split()]
    A = [int(a) for a in input().split()]
    solve(N, K, A)

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
def warp(x,k):
    a=x
    for i in range(k):
        a=A[a-1]
    return a
count=[-1 for i in range(N)]
x=1
count[0]=0
time=0
if N>=K:
    print(warp(1,K))
else:
    for i in range(1,N+1):
        x=warp(x,1)
        if count[x-1]==-1:
            count[x-1]=i
        else:
            time=i-count[x-1]
            break;
    print(warp(1,count[x-1]+(K-count[x-1])%time))

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
now=1
arr=[0]*(n+1)
for i in range(1,10**6):
  now=a[now-1]
  if i==k:
    print(now)
    quit()
  if arr[now]!=0:
    first=arr[now]
    break
  arr[now]=i

cycle=max(arr)-first+1

mod=(k-first)%cycle

ans=arr.index(first+mod)
print(ans)

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

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

costs = [-1] * N
loc = 1

if K <= N:
    for i in range(K):
        loc = A[loc - 1]
    print(loc)

else:
    costs[loc - 1] = 0
    for i in range(1, K):
        loc = A[loc - 1]

        if costs[loc - 1] >= 0:
            break

        costs[loc - 1] = i

    offset = costs[loc - 1]
    loop = i - offset

    K -= i
    K %= loop

    for _ in range(K):
        loc = A[loc - 1]
    print(loc)

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

while 1:
    cnt+=1
    pl=a[pl-1]
    if visit[pl-1]!=-1:
        loop=visit[pl-1]
        break
    visit[pl-1]=cnt
    if cnt==k:
        print(pl)
        exit()

loop_len=cnt-loop
k=(k-loop)%loop_len+loop
print(visit.index(k)+1)

Solution (Python):
def resolve():
    n, k = map(int, input().split())
    A = list(map(int, input().split()))
    s = []
    ord = [-1 for i in range(n + 1)]
    rep = 1
    pos = 1
    while ord[pos] == -1:
        ord[pos] = len(s)
        s.append(pos)
        pos = A[pos - 1]
        rep += 1

    rep = len(s) - ord[pos]
    
    l = ord[pos]
    if k < l:
        print(s[k])
    else:
        
        k -= l
        k %= rep
        print(s[l + k])
resolve()

Solution (Python):
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate, product, combinations_with_replacement
import sys
import bisect
import string
import math
import time


def I(): return int(input())
def S(): return input()
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return [int(i) for i in input().split()]
def LI_(): return [int(i)-1 for i in input().split()]
def StoI(): return [ord(i)-97 for i in input()]
def ItoS(nn): return chr(nn+97)
def input(): return sys.stdin.readline().rstrip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def print_matrix(mat):
    for i in range(len(mat)):
        print(*['IINF' if v == IINF else "{:0=4}".format(v) for v in mat[i]])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False



def main():
    D = 60
    N, K = MI()
    A = LI()
    edges = [[] for i in range(N)]
    to = [[0] * N for i in range(D)]

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

    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)

if __name__ == '__main__':
    main()

Solution (Python):
import logging

logging.basicConfig(level=logging.INFO, format="%(message)s")



def main():
    N, K = map(int, input().split())
    A_i = list(map(int, input().split()))
    B_i = [0 for i in range(N)]
    cycle_list = []
    diff_list = []
    cycle = 0
    diff = 0
    counter = 0
    machi = 1

    while counter < N:
        if B_i[machi - 1] == 1:
            diff = cycle_list.index(machi)
            cycle = counter - diff
            diff_list = cycle_list[:diff]
            cycle_list = cycle_list[diff:]
            break
        else:
            counter += 1
            B_i[machi - 1] = 1
            cycle_list.append(machi)
            machi = A_i[machi - 1]

    if K < diff:
        print(diff_list[K])
    else:
        mod_K = (K - diff) % cycle
        print(cycle_list[mod_K])

if __name__ == "__main__":
    main()

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

order = [-1] * N
s = []
now = 0
c = 0
a = None
b = None
while True:
    order[now] = c
    s.append(now)
    now = A[now]
    c += 1
    if order[now] >= 0:
        a = c - order[now]
        b = order[now]
        break
if K <= b:
    print(s[K] + 1)
else:
    K -= b
    K %= a
    print(s[K + b] + 1)

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

doubling = [[0] * N for _ in range(61)]
for i in range(N):
  doubling[0][i] = A[i]
  
for i in range(1,61):
  for j in range(N):
    doubling[i][j] = doubling[i-1][doubling[i-1][j]]
    
now = 0
i = 0
while K!=0:
  if K&1==1:
    now = doubling[i][now]
    K = K>>1
    i += 1
    
  else:
    K = K>>1
    i += 1
    
print(now+1)

Solution (Python):
import numpy as np
N, K = list(map(int, input().split()))
A = np.array(list(map(int, input().split()))) - 1
mem = {}

c = 0 
cK = 0 
flg = True
mem[c] = 0
for k in range(1, K+1):
    c = A[c] 
    if c in mem:
        T = k - mem[c]
        cK = k
        flg = False
        break
    mem[c] = k

if flg:
    print(c+1)
else:
    iterN = int(np.mod(int(K - cK), int(T)))
    for i in range(iterN):
        c = A[c]
    print(c+1)

Solution (Python):
N, k = map(int, input().split())
a = 1
b = [bi - 1 for bi in map(int, input().split())]
a -= 1

now = b[a]
S = set()
S.add(a)
while now not in S:
    S.add(now)
    now = b[now]
root = now

count = 1
now = b[root]
while now != root:
    now = b[now]
    count += 1

start = len(S) - count

if k <= start:
    now = a
    for _ in range(k):
        now = b[now]
    print(now + 1)
else:
    k -= start
    k %= count
    now = root
    for _ in range(k):
        now = b[now]
    print(now + 1)

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:
    print(journey[K])
    exit()

loop_start = N-1
loop_end   = N
 
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):
N, K = map(int, input().split())
A = tuple(map(lambda n: int(n) - 1, input().split()))

costs = [-1] * N
loc = 0

if K <= N:
    for i in range(K):
        loc = A[loc]
    print(loc + 1)

else:
    costs[loc] = 0
    for i in range(1, K):
        loc = A[loc]

        if costs[loc] >= 0:
            break

        costs[loc] = i

    offset = costs[loc]
    loop = i - offset

    K -= i
    K %= loop

    for _ in range(K):
        loc = A[loc]
    print(loc + 1)

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 d():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    
    warps = [1]
    w = {}

    for i in range(K):
        city = A[warps[-1] - 1]
        
        if city in w:
            lsi = warps.index(city)
            Kn = (K - lsi) % (len(warps) - lsi)
            print(warps[lsi + Kn])
            return
        else:
            warps.append(city)
            w[city] = city
    print(warps[-1])


def dd():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    v = []
    w = {}
    now = 0
    for i in range(K):
        print('i, v, w, now = {}, {}, {}, {}'.format(i, v, w, now))
        p = A[now]
        now = p-1
        if p in w:
            j = v.index(p)
            df = i-j
            Kn = (K-i-1) % df
            p = v[j+Kn]
            break
        else:
            v.append(p)
            w[p] = p
    print(p)



if __name__ == "__main__":
    d()

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

while 1:
    cnt+=1
    pl=a[pl-1]
    if visit[pl-1]!=-1:
        loop=visit[pl-1]
        break
    visit[pl-1]=cnt
    if cnt==k:
        print(pl)
        exit()

loop_len=cnt-loop
q=True
k=(k-loop)%loop_len+loop
print(visit.index(k)+1)

Solution (Python):
n, k = map(int, input().split())
As = list(map(int, input().split()))
maps = {}

for i, a in enumerate(As):
    maps[i] = a - 1

probs = [0] * n
p = 0  
target = 0  
h = 0  
t = 0  


for i in range(n + 1):
    probs[p] += 1
    if (probs[p] == 2):
        target = p
        t = i
        break
    p = maps[p]


p = 0
for i in range(n):
    if (p == target):
        h = i
        break
    p = maps[p]

s = t - h  
if (k <= h):
    p = 0
    for i in range(k):
        p = maps[p]
    print(p + 1)
    exit()

d = (k - h) % s  


p = 0
for i in range(h + d):
    p = maps[p]

print(p + 1)

Solution (Python):
def resolve():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    check=[-1]*n
    iti=0
    rireki=[]
    while True:
        iti=a[iti]-1
        if check[iti]==0:
            mae=rireki.index(iti)
            Mae=rireki[:mae]
            Loop=rireki[mae:]
            roop=len(Loop)
            break
        rireki.append(iti)

        check[iti]=0
    if k <= mae:
        print(Mae[k-1]+1)
    else:
        k-=mae
        print(Loop[(k%roop)-1]+1)
resolve()

Solution (Python):

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

loop = []
loop_corr = []
ord = [-1]*n
curr = 0
while ord[curr] == -1:
    ord[curr] = len(loop)
    loop.append(curr)
    curr = a[curr]
        
loop_corr = loop[loop.index(curr):len(loop)]



if len(loop) > k:
    print(loop[k]+1)
else:
    diff = k - len(loop) + 1
    mod = (diff % len(loop_corr)) -1
    
    
    print(loop_corr[mod]+1)

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

check = [0]*N
i = 0
c = 1
check = []
visited = [0]*N
flag = False
while c<=K:
    if visited[i] == 1:
        flag = True
        break
    else:
        check.append(i)
        visited[i] = 1
        i = A[i]
        c += 1
if flag==True:
    X = check[check.index(i):]
    print(1+X[(K-check.index(i))%len(X)])  
else: 
    print(i+1)