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):
ii = lambda:int(input())
mi = lambda:list(map(int,input().split()))
ix = lambda x:list(input() for _ in range(x))
mix = lambda x:list(mi() for _ in range(x))
iix = lambda x:list(int(input()) for _ in range(x))

def main(n,k,a):
    zan = 0
    count = 0
    p = 1
    t = {i:-1 for i in range(n)}
    t[0] = 0
    for i in range(k):
        count += 1
        p = a[p-1]
        if t[p-1] == -1 :
            t[p-1] = count
        else:
            loop = count - t[p-1]
            zan = (k- t[p-1]) % loop
            break
    for i in range(zan):
        p = a[p-1]
    return p

n,k = mi()
a = mi()
print(main(n,k,a))

Solution (Python):
n,k=map(int, input().split())
a = list(map(int, input().split()))
t = [0 for i in range(n)]
now = a[0] -1
t[0] = 1
root = [0]
for i in range(0,k):
    if t[now] == 0:
        root.append(now)
        t[now] = 1
        now = a[now] -1
    else:
        break
if len(root)- 1 == k:
    print(root[-1]+1)
else:
    for i in range(0,len(root)):
        if root[i] == now:
            b = len(root) - i
            c = (k-i)%b
            print(root[i+c]+1)

Solution (Python):
N, K = [int(x) for x in input().split()]
A = [int(x)-1 for x in input().split()]
past = 0
history = [0]
s = set()
while True:
    na = A[past]
    if na in s: 
        break
    s.add(na)
    history.append(na)
    past = na
s = history.index(na)
e = len(history)
loop = e - s
if K <= s: 
    print(history[K]+1)
else:
    k = K - s
    print(history[s+(k%loop)]+1)

Solution (Python):
n, k = [int(_) for _ in input().split()]
a = [int(_) for _ in input().split()]

t = 0
l = []
c = 0
d = {}
while True:
    d[t+1] = c
    c += 1
    l.append(t+1)
    t = a[t] - 1
    
    
    if t + 1 in d:
        s = l[d[t+1]:]
        q = d[t+1]
        break





if k <= q:
    print(l[k])
else:
    print(s[(k-q) % len(s)])

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
now = 1
flag = [False] * N
c = 0
temp = [0]*N
hoge = False
for i in range(K):
    if flag[now-1]:
        hoge = True
        break
    temp[now-1] = i
    flag[now-1] = True
    now = A[now-1]
    c += 1
if hoge:
    c -= temp[now-1]
    K -= temp[now-1]
    for _ in range(K%c):
        now = A[now-1]
print(now)

Solution (Python):
import itertools
from collections import defaultdict
import collections
import sys
sys.setrecursionlimit(200000)
mod = 1000000007

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

tf = [False] * (n + 1)
tf[1] = True
ss = [1]
cnt = 0
while cnt < max(k,n ** 2):
    if len(ss) != 1 and tf[a[ss[cnt] - 1]]:
        d = a[ss[cnt] - 1]
        break
    tf[a[ss[cnt] - 1]] = True
    ss.append(a[ss[cnt] - 1])
    cnt += 1

if len(ss) > k:
    print(ss[k])
else:
    sss = ss.index(d)
    print(ss[sss+(k -len(ss)) % (len(ss) - sss)])

Solution (Python):
n , k = map(int, input().split())
a = list(map(int,input().split()))
v = [0]*(n+1)
v[1]=1
v2=[1]
i=0
step=1

while True:
    if v[a[i]]!=0:
        loop=step-v[a[i]]+1
        loopstart=v[a[i]]
        break
    else:
        step+=1
        v[a[i]]=step
        v2.append(a[i])
        i=a[i]-1
ans = (k-loopstart+2)%loop
if ans ==0:
    ans+=loop
if k<loopstart:
    print(v2[k])
    exit()
v2=v2[loopstart-1:]
print(v2[ans-1])

Solution (Python):
import math
import fractions



def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  
factinv = [1, 1]  
inv = [0, 1]  

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''










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

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

now = 0
count = 0
route = [0]
done = [-1 for i in range(n)]
done[0]= 0
roopStart = -1
roopLen = -1
while(True):
    now = a[now]
    route.append(now)
    count+=1
    if(done[now]>=0):
        roopStart = now
        roopLen = count - done[now]
        break
    else:
        done[now] = count

        



if(k<done[roopStart]):
    
    print(route[k]+1)
else:
    
    
    print(1+route[done[roopStart] + (k-done[roopStart])%roopLen])

Solution (Python):
def solve(n, k, a):
    ori_k = k

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

    path = [1]
    cur_town = 1
    visited = set()
    visited.add(1)

    before_cycle = None
    while k > 0:
        k -= 1
        cur_town = mapper[cur_town]
        if k == 0:
            return cur_town
        if cur_town in visited:
            before_cycle = path.index(cur_town)
            path = path[path.index(cur_town):]
            break
        
        path.append(cur_town)
        visited.add(cur_town)

    
    
    
    result = path[(ori_k-before_cycle) % len(path)]
    return result



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

Solution (Python):
N,K = map(int,input().split())
As = [int(e)-1 for e in input().split()]
visited=[0]*N

town = 0
for k in range(K):
    town = As[town]

    if visited[town] > 0:
        break
    
    visited[town] = k+1

else:
    print(town+1)
    exit()

K = K-visited[town]
K=K%((k+1)-visited[town])


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

print(town+1)

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
lis = [-1] * len(A)
nex = 1
start = 0
loop = 0
result = -1
for i in range(len(A)):
    if i == K:
        result = nex
    if lis[nex-1] ==-1:
        lis[nex-1]=i
        nex = A[nex-1]
    else :
        start = nex
        loop = i - lis[nex-1]
        break
nex = start
end = (K-lis[start-1])%loop
for i in range(end):
    nex = A[nex-1]
if result ==-1:
    result = nex
print(result)

Solution (Python):
n,k=map(int,input().split())
a=list(map(int,input().split()))
visited=set()
new=0
c=0
while not new in visited and c<k:
  visited.add(new)
  new=a[new]-1
  c+=1
if c==k:
  print(new+1)
else:
  start=new
  d=0
  visited=set()
  while not new in visited and d<k-c:
    visited.add(new)
    new=a[new]-1
    d+=1
  if k-c==d:
    print(new+1)
  else:
    new=start
    for i in range((k-c)%d):
      new=a[new]-1
    print(new+1)

Solution (Python):





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





fresh = ['a'] + [True] * N 
fresh[1] = False
turn = ['a'] + [0] * N 
status = True



def search_loop():
    log = [1] 
    last  = 1 
    counter = 0
    while status:
        next_spot = A[last - 1]
        counter += 1
        
        if(fresh[next_spot]):
            
            log.append(next_spot)
            last = next_spot
            fresh[next_spot] = False
            turn[next_spot] = counter
        else:
            log.append(next_spot)
            last = next_spot
            fresh[next_spot] = False
            
            break
    return log, last, turn, counter
    



if(A[0] == 1):
    
    ans = 1
else:
    loop, loop_folder, kiroku, count = search_loop()
    
    
    x = kiroku[loop_folder]
    p = count - x 
    
    if(K < x):
        ans = loop[K]
    else:
        l = loop[x:count]
        L = K - x
        mod = L % p
        
        
        ans = l[mod]
print(ans)

Solution (Python):
import sys

def main():
    N, K = map(int, input().split())
    A_list = list(map(int, input().split()))
    A_list = [x-1 for x in A_list]

    passed_list = [False] * N
    time_go_same_city = 0
    now_city = 0
    passed_list[now_city] = True
    while True:
        next_city = A_list[now_city]
        if passed_list[next_city]:
            start_circle_city = next_city
            break
        passed_list[next_city] = True
        time_go_same_city += 1
        now_city = next_city

    passed_list = [False] * N
    time_circle_city = 1
    now_city = start_circle_city
    passed_list[now_city] = True
    while True:
        next_city = A_list[now_city]
        if passed_list[next_city]:
            break
        passed_list[next_city] = True
        time_circle_city += 1
        now_city = next_city

    if time_go_same_city >= K:
        num_teleport = 0
        now_city = 0
        while num_teleport < K:
            next_city = A_list[now_city]
            num_teleport += 1
            now_city = next_city
        print(now_city+1)
        return
    
    K -= time_go_same_city
    K %= time_circle_city
    if K == 0:
        K = time_circle_city
    num_teleport = 1
    now_city = start_circle_city
    while num_teleport < K:
        next_city = A_list[now_city]
        num_teleport += 1
        now_city = next_city

    print(now_city+1)
    return


if __name__ == "__main__":
    main()
    sys.exit(0)

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

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

tel_list = []

next_city = 0

city_have_been_to = set([0])

way = [0]

while k > 0:
    k -= 1
    temp = len(city_have_been_to)

    next_city = a[next_city] - 1
    city_have_been_to.add(next_city)
    way.append(next_city)

    if temp == len(city_have_been_to):
        break

if k == 0:
    print(way[-1] + 1)
else:
    temp_index = way.index(next_city)
    print(way[temp_index:-1][k % len(way[temp_index:-1])] + 1)

Solution (Python):



def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    

    def dump(*args):
        sys.stderr.write(str(args))

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

    nex = a[0] - 1
    now = 0
    turn = 0

    mode = False

    while True:
        if not mode and pos[nex] == -1:
            if turn == k:
                print(now+1)
                exit(0)
            pos[nex] = pos[now] + 1
            now = nex
            nex = a[nex] - 1
            turn += 1
            continue
        if mode:
            if turn == k:
                print(now+1)
                exit(0)
            pos[nex] = pos[now] + 1
            now = nex
            nex = a[nex] - 1
            turn += 1
            continue
        circle = turn - pos[nex] + 1
        turn += (k-turn) // circle * circle
        mode = True

    


if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int, input().split())
a = list(map(lambda x: int(x) - 1 , input().split()))
b = [0]
z = [-1] * n
idx = 1
z[0] = idx
aloop = True
c = 0
while True:
    c = a[c]
    if z[c] > -1:
        break
    b.append(c)
    idx += 1
    z[c] = idx



ll = idx - z[c] + 1

dd = z[c] - 1
if k < dd:
    print(b[k]+1)
    exit()


print(b[(k - dd) % ll + dd]+1)

Solution (Python):

import sys

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

    count = 1
    now = 0
    visited = [1]
    set_v = set()
    set_v.add(1)
    l = -1
    while count < N:
        x = A[now]
        if x in set_v:
            l = visited.index(x)
            break
        else:
            count += 1
            visited.append(x)
            set_v.add(x)
            now = x-1
    r = count
    
    
    if K < l:
        print(visited[K])
    else:
        print(visited[l + (K-l) % (r-l)])

if __name__ == '__main__':
    main()

Solution (Python):
from sys import stdin
def main():
    
    readline=stdin.readline
    n,k=map(int,readline().split())
    a=list(map(lambda x:int(x)-1,readline().split()))

    flags=[False]*n

    now=0
    cnt=0
    while True:
        flags[now]=True
        cnt+=1
        nex=a[now]
        if flags[nex]:
            last=now
            break
        else:
            now=nex

    f_cnt=cnt
    cnt=0
    while True:
        nex=a[now]
        if nex==last:
            cnt+=1
            break
        else:
            now=nex
            cnt+=1

    l=k-(f_cnt-cnt)
    if l<0:
        now=0
        for _ in range(k):
            now=a[now]
        print(now+1)
    else:
        l%=cnt
        now=a[last]
        for _ in range(l):
            nex=a[now]
            now=nex

        print(now+1)
if __name__=="__main__":
    main()

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

    base, cycle = 0, 0
    order = [-1] * N
    order[0] = 0
    cnt = 1
    idx = A[0] - 1
    while True:
        if order[idx] == -1:
            order[idx] = cnt
            cnt += 1
            idx = A[idx] - 1
            continue
        base = order[idx]
        cycle = cnt - order[idx]
        break

    if base + cycle <= K:
        rest = (K - base) % cycle
        ans = order.index(base + rest) + 1
    else:
        ans = order.index(K) + 1
    print(ans)

abc167_d()

Solution (Python):

 
nk = list(map(int,input().split()))
N, K = nk[0], nk[1]

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


if ( N < K ):	
  cur = 1
  count = 0
  A_chk = [0] * len(A)
  
  while ( A_chk[cur-1]==0 ):
    A_chk[cur-1] = 1	
    cur = A[cur-1]		
    count += 1			
    
  
  
  loop_s = cur		
  count_b = count	
  
  cur = 1
  count = 0
  while ( cur != loop_s ):
    cur = A[cur-1]
    count += 1
  
  
  before_loop_count = count
  loop_count = count_b - count
  
  
  K_re = ( K - before_loop_count ) % loop_count
  
  
  cur = loop_s
  for i in range(K_re):
    cur = A[cur-1]
  print(cur)
  
else:	
  cur = 1
  for i in range(K):
    cur = A[cur-1]
    
  print(cur)

Solution (Python):
from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

import os, sys, bisect, copy
from collections import defaultdict, Counter, deque

if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')

def input(): return sys.stdin.readline()
def mapi(arg=0): return map(int if arg==0 else str,input().split())

import sys
sys.setrecursionlimit(10**6)
from types import GeneratorType

def bootstrap(func, stack=[]):
    def wrapped_function(*args, **kwargs):
        if stack:
            return func(*args, **kwargs)
        else:
            call = func(*args, **kwargs)
            while True:
                if type(call) is GeneratorType:
                    stack.append(call)
                    call = next(call)
                else:
                    stack.pop()
                    if not stack:
                        break
                    call = stack[-1].send(call)
            return call
    return wrapped_function


n,k = mapi()
a = [0]+list(mapi())
gr = defaultdict(int)
for i in range(1,n+1):
    gr[i]=a[i]

vis ={}
path = []
p = 1

@bootstrap
def dfs(s):
    global p
    if s in vis:
        p = s
        yield 0
    path.append(s)
    vis[s] = 1
    res =0
    res+= yield dfs(gr[s])
    yield res
dfs(1)
i = 0
ln = 0
path2 = path[:]
while i<len(path):
    if p==path[i]:
        path2 = path2[i:]
        break
    i+=1

if k<len(path)-len(path2):
    print(path[k])
else:
    k -= len(path)-len(path2)
    print(path2[k%len(path2)])

Solution (Python):
pi = 3.1415926


def inp():
    return(int(input().rstrip()))
def inlt():
    return(list(map(int,input().rstrip().split())))
def insr():
    s = input().rstrip()
    return(s[:len(s) - 1])
def invr():
    return(map(int,input().rstrip().split()))

n,k = invr()
nums = [0] + inlt()
cycle = [nums[1]]
s = set([cycle[0]])
bp = 0
for i in range(2*n):
    if nums[cycle[-1]] not in s:
        s.add(nums[cycle[-1]])
        cycle.append(nums[cycle[-1]])
        
    else:
        bp = nums[cycle[-1]]
        break

if k <= len(cycle):
    print(cycle[k - 1])
else:
    if bp != 0:
        for i in range(len(cycle)):
            if cycle[i] == bp:
                cycle = cycle[i:]
                break
    k -= i
    remain = k % len(cycle)
    print(cycle[remain - 1])

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

hant = [0 for i in range(n)]
add = [1]
now = 1
hant[0]= 1
count = 1
for i in range(max(n,k)):
    now = A[now-1]
    add.append(now)
    
    count+=1
    if hant[now-1] == 0:
        hant[now-1] = count
    else:
        syuki = count-hant[now-1]
        amari = hant[now-1]-1
        break

rep = add[amari:syuki+amari]



if k>=amari:
    ind = (k-amari)%syuki
    print(rep[ind])
elif k<amari:
    print(add[k])

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

ans=[]
judge={}
j=0 
while A[j] not in judge.keys() or judge[A[j]]!=2:
    ans.append(A[j])
    if A[j] not in judge.keys():
        judge[A[j]]=0
    judge[A[j]]+=1
    j=A[j]-1

st=ans.index(A[j])

if st<K:
    ans=ans[st:]
    K-=st
    l=len(ans)
    
    print(ans[K%l-1])
else:
    print(ans[K-1])

Solution (Python):

import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

n, k =MAP()

a = LIST()





i=0
j = 1
dd = defaultdict(int)
dd[1] = 0
while(True):
    if(a[i] in dd):
        pos = dd[a[i]]
        break
    dd[a[i]] = j
    i = a[i]-1
    j+=1

suited = list(dd.keys())[pos:]
temp = j-pos
if(k>=pos):
    k-=pos
    k = k%temp

    print(suited[k])
else:
    newS = list(dd.keys())[:pos]
    print(newS[k])

Solution (Python):
N,K = map(int,input().split())
a = list(map(int,input().split()))
town = [-1]*N
i=1
n=0
while True:
    if town[i-1] == -1:
        town[i-1] = n
        i = a[i-1]
    else:
        roop = i
        break
    n += 1

amari = (K-town[roop-1])%(n-town[roop-1])
if K-town[roop-1]>0:
    print(town.index(town[roop-1]+amari)+1)
else:
    print(town.index(K)+1)

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

list=[-1]*n
list[1-1]=0 

p=1
count=0
end=False

while True:
    count+=1
    p=A[p-1]
    if count==k:
        end=True
        break

    if list[p-1]==-1:
        list[p-1]=count
    else:
        loop=count-list[p-1]
        break

if end==False:
    count+=loop*(((k-count)//loop)-1)
    while True:
        count+=1
        p=A[p-1]
        if count==k:
            end=True
            break

print(p)

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

town = 0
visited = [town]
index = 0
visited_index = {town: index}
loop = None
while K > 0:
    K -= 1
    town = A[town]
    if town in visited_index:
        loop = visited[visited_index[town]:]
        break
    visited.append(town)
    index += 1
    visited_index[town] = index

if loop:
    K %= len(loop)
    print(loop[K]+1)
else:
    print(town+1)

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

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

graph = []

time = [-1] * N

now = 0
nex = 0
time[0] = 0
loop = 0

while True:
    now = nex
    nex = A[now] - 1

    if time[nex] == -1:
        time[nex] = time[now] + 1
    else:
        loop = nex
        break

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

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