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



Sample input:
4 5
3 2 4 1


Sample output:
4

Submission status: Runtime Error

Solution code:
#import sys
MOD = 10 ** 9 + 7
INFI = 10**10
#input = sys.stdin.readline
import math

import itertools
import heapq
#import bisect

import copy
from functools import lru_cache

def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

#    h,w,a,b = map(int, input().split())
#    c = [[0 for j in range(n)] for i in range(n)]

def ret(a):
    c=[None]*(len(a)-1)
    if len(a)==1:
        return a[0]
    elif len(a)==0:
        return 0
    for i in range(1,len(a)):
        c[i-1]=abs(a[i]-a[i-1])
    return ret(c)


def main():
    n,k=map(int,input().split())
    a =list(map(int,input().split()))
    town=[-1 for _ in range(n)]
    town[0]=0
    now=0
    for i in range(n):
        if town[a[now]-1]==-1:
            town[a[now]-1]=i+1
            now=a[now]-1
        else:
            sec=a[now]-1
            break
    town2 = [-1 for _ in range(n)]
    town2[sec] = 0
    now = sec
    for i in range(n):
        if town2[a[now] - 1] == -1:
            town2[a[now] - 1] = i + 1
            now = a[now] - 1
        else:
            thi = a[now] - 1
            break
#    print(town)
#    print(town2)
    firstloop=max(town)+1
    secondloop=max(town2)+1
    ans=0
    if k<=firstloop:
        ans=town.index(k)+1
    else:
        k-=firstloop
        kai=k//secondloop
        k-=kai*secondloop
        ans=town2.index(k)+1
    print(ans)

if __name__ == "__main__":

    main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
tmp = a[0]
tmp0 = tmp
x = 0

for i in range(k-1):
    tmp = a[tmp-1]
    if tmp == tmp0:
        x = i
        break

ans = a[0]
for i in range(k % x):
    ans = a[ans-1]
print(ans)

Submission status: Runtime Error

Solution code:
S=lambda:input()
I=lambda:int(input())
L=lambda:list(map(int,input().split()))
LS=lambda:list(map(str,input().split()))

def main():
    import sys
    input = sys.stdin.readline
    n,k=L()
    a=L()
    visited=[0]*n
    tmp=0
    now=0
    visited[0]=1
    for i in range(k):
        now=a[i]-1
        #print(tmp,now+1)
        if visited[now]==0:
            visited[now]=1
        else:
            tmp=i
            break
    #print(tmp,now)
    tmp2=k%tmp
    dist=a[now]
    #print(now+1,end=" ")
    for i in range(tmp2):
        now=a[now]-1
        dist=now+1
        #print(now+1,end=" ")
    #print()
    print(dist)
    
    
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
A = list(map(int, input().split())) 
check = [0]*N
tele_lis = []
global start
start = []
def tele(x):
    check[x-1] = 1
    tele_lis.append(x)
    if check[A[x-1]-1] == 0:
        tele(A[x-1])
    else:
        start.append(A[x-1])
        return
tele(1)
for i in range(N):
    if start[0] == tele_lis[i]:
        break
    
print(tele_lis[i::][(K-i) % (sum(check)-i)])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
dir = a[0]
hash_a = [False for _ in range(n)]
hash_a[0] = True
cnt = 0
while True:
    k -= 1
    cnt += 1
    if k == 0:
        break
    dir = a[dir - 1]
    if not hash_a[dir - 1]:
        hash_a[dir - 1] = True
    else:
        k %= cnt - 1
print(dir)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split(' '))
A=list(map(lambda x:int(x)-1,input().split(' ')))
roop=[0]
flg = [0 for i in range(N)]
n = A[0]
cnt = 0
while not flg[n] and n !=0:
    cnt += 1
    roop.append(n)
    flg[n]=cnt
    n = A[n]
if K<=len(roop):
    print(roop[K])
else:
    print(roop[flg[n]:cnt+1][(K-flg[n])%(cnt-flg[n]+1)]+1)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
a = list(map(int, input().split()))
chk = [0] * N
start = -1
ido = [0]
chk[0] = 1
index = 0
cnt = 0
while True:
    index = a[index] - 1
    if chk[index] == 0:
        chk[index] += 1
        cnt += 1
        ido.append(index)
    else:
        start = index
        break

if cnt > K:
    print(a[ido[K]])
    exit()
tmp = ido.index(start)
ido = ido[index:]
K -= tmp
print(ido[K % len(ido)] + 1)

Submission status: Runtime Error

Solution code:
N,K=map(int, input().split())
A=list(map(int, input().split()))
import sys
sys.setrecursionlimit(10**6)
import numpy as np
done=np.array([0]*N)
X=[0]*2
L=[]
F=[True]
def dfs(start, steps):
    done[start-1]+=1
    L.append(start)
    if done[start-1]==3:
        X[1]=steps
        return
    elif done[start-1]==2 and F[0]:
        X[0]=steps
        F[0]=False
    nex=A[start-1]
    dfs(nex, steps+1)
dfs(1,0)
#print(done)
#print(X)
#print(L)
first=L[:X[0]-(X[1]-X[0])]
sec=L[X[0]-(X[1]-X[0]):X[0]-(X[1]-X[0])+(X[1]-X[0])]
#print(first, sec)
if len(first)==0:
    first=sec
if K-1<=len(first):
    print(first[K])
else:
    K=K-len(first)
    print(sec[(K%len(sec))])

Submission status: Runtime Error

Solution code:
import sys
n,k=map(int,input().split())
A=[int(i) for i in input().split()]
d=dict()
for i,a in enumerate(A):
    d[i+1] = a
p=1
li = set()
li.add(1)
for i in range(k):
    #print(p,li)
    p = d[p]
    #print(p,li)
    if p in li:
        cyc =  i+ 1- pidx
        q = 1
        st=0
        while q != p:
            q = d[q]
            st+=1
        k = (k-st) % cyc + st
        r = 1
        #print(k)
        for _ in range(k):
            #print(r)
            r = d[r]
        print(r)
        sys.exit()
    li.add(p)
else:
    print(p)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
origin = 1
now = origin
for i in range(k):
    new = a[now-1]
    now = new
    if now == origin:
        mod = k % i
        for j in range(mod):
            now = a[now-1]
            now = new
print(now)

Submission status: Runtime Error

Solution code:
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
#     combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
INF = 1<<29
lINF = 1<<35

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

def main():
    n,k = readInt()
    a = readInt()
    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
    
    roop.reverse()
    num = 0
    if len(move)>=k:
        print(move[k]+1)
    else:
        num = (k - (len(move)-len(roop))) % len(roop)
        print(roop[num]+1)
    return

if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
town=1
townhairetu=[1]
n=0
for i in range(K):
	town=A[town-1]
	if(town in townhairetu):
		n=i+1-townhairetu.index(town)
		break
	else:
		townhairetu.append(town)
print(townhairetu[(K-townhairetu.index(town))%n+townhairetu.index(town)])

Submission status: Runtime Error

Solution code:
import collections
n, k = map(int, input().split())
A = list(map(int, input().split()))
A = [i-1 for i in A]
N = collections.Counter()
t = 0
cnt = 0
for i in range(k):
    if N[t]:
        break
    N[t] = 1
    t = A[t]
    cnt += 1
k -= cnt
T = []
for i in N:
    T.append(i)
tmp = T.index(t)
S = T[tmp:]
s_len = len(S)
ind = k % s_len
print(S[ind] + 1)

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n,k = na()
a = na()
dp = [-1]*n
dp[0] = 0
i = 1
now = 0
loop = -1
start = -1

while True:
    now = a[now]-1
    if i == k:
        print(now+1)
        exit()
    if dp[now] == -1:
        dp[now] = i
    else:
        loop = i - dp[now]
        start = now
        break
    i+=1

print(dp.index((k-start)%loop+start)+1)

Submission status: Runtime Error

Solution code:
import math
n,k=map(int, input().split())
a_lis=[map(int,input().split())]
direct={ i+1:a_lis[i] for i in range(n)}

d_lis=[1]
j=direct[1]
while True:
  d_lis.append(j)
  j=direct[j]
  if j==1:
    break

dp=d_lis*(math.floor(k/len(d_lis))+1)

print(dp[k-1])

Submission status: Runtime Error

Solution code:
def main():
    import sys
    N,K=list(map(int,sys.stdin.readline().split()))
    A=list(map(int,sys.stdin.readline().split()))
    A=[1]+A
    route=[1]
    st=set()
    st.add(1)
    now=1
    while True:
        now=A[now]
        if now in st:
            break
        route.append(now)
        st.add(now)
    
    idx=route.index(now)
    if K-idx+1>0:
        if len(route)-1!=idx:
            print(route[idx-1+(K-idx+1)%(len(route)-idx)])
        else:
            raise Exception
            return
            print(route[-1])
    else:
        while True:
            A.append(0)
        print(route[K])
    

main()

Submission status: Runtime Error

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

A = list(map(int,input().split()))
t = 0
c = 0
ans = [0] * n
L = []
for _ in range(k):
    if ans[t] == 1:
        t += k%c
        t %= n
        t = L[t]
        break
    else:
        ans[t] = 1
        L.append(t)
        t = A[t]-1
        c += 1
print(t+1)

Submission status: Runtime Error

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

count = 0
location = 0
footprints = []
while(True):
    k -= 1
    footprints += [location]
    location = a[location]
    print(k, footprints, location)
    
    if (k == 0):
        print(location+1)
        break
    
    if (location in footprints):
        x = footprints.index(location)
        loop = footprints[x:]
        n = len(loop)
        print(loop[k%n]+1)
        break

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

N, K = mi()
A = li()
flag = [0]*N
l = []
i = 1
ind = 0
while True:
    #print(ind, flag)
    flag[ind] = i
    l.append(ind+1)
    if not flag[A[ind]-1]:
        ind = A[ind]-1
    else:
        ind = A[ind]-1
        break
    i += 1

if K < flag[ind] -1:
    print(l[K])
    exit()

if ind != 0:
    K -= flag[ind] -1
    i -= flag[ind] -1
    print(l[K%i+i-1])
else:
    print(l[K%i])

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split(" "))
a = list(map(int,input().split(" ")))
memory = [1]
i = 1
while True:
  if not a[i-1] in memory:
    memory.append(a[i-1])
    i = a[i-1]
  else:
    start = memory.index(a[i-1])
    break
if k < len(memory):
  print(memory[k-1])
else:
  loop = len(memory)-start
  town = (k - start) % loop
print(memory[town + start])

Submission status: Runtime Error

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
import sys
from bisect import bisect_left, bisect_right, insort
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def MS(): return map(str,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())
#N = I()
#A = [LI() for _ in range(N)]

n,k = MI()
a = LI()
ans = [1] * n
memo = [-1] * n
memo[0] = 0
s = 0
for i in range(1,n):
    if memo[a[ans[i-1]-1]-1] == -1:
        ans[i] = a[ans[i-1]-1]
        s += 1
        memo[ans[i] - 1] = s

    else:
        t = memo[a[ans[i-1]-1]-1]
        break
if k <= t:
    print(ans.index(k) + 1)
elif t == 0:
    print(ans[(k - 1) % (s-t +1) +1])
else:
    print(ans[(k-(t-1)-1) % (s-t+1) + t])

Submission status: Runtime Error

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

stayed = [0] * (n+1)

A = list(map(int, input().split()))
start = 0
stayed[0] = 1
roops = 0
ANS = []
for i in range(n+1):
    if stayed[A[start] - 1] == 0:
        stayed[A[start] - 1] = 1
        start = A[start] - 1
        ANS.append(start)
        roops += 1
    else:
        break
index_ = ANS.index(start - 1)
before_roop = index_ + 1
if index_ == 0:
    before_roop = 0
true_roop = len(ANS) - index_

if true_roop + before_roop >= k:
    ANS = [0] + ANS + [start -1]
    print(ANS[k] + 1)
else:
    k = k - before_roop
    k = k % true_roop
    ANS = ANS[index_:]
    print(ANS[k] + 1)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
f = [0 for _ in range(n)]
f[0] = 1

v = [1]
s = 0
idx = 0
loop = 0
last = 1
for i in range(k):
    vi = a[last - 1]
    if not f[vi - 1]:
        f[vi - 1] = 1
        last = vi
        s += 1
        v.append(vi)
    else:
        s += 1
        idx = v.index(vi)
        loop = s - idx
        break
remain = k - s
print(v[idx:][remain % loop])

Submission status: Runtime Error

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

init = [1]
while True:
    nxt = a[init[-1]-1]
    if nxt in init:
        idx_nxt = init[nxt]
        loop = init[idx_nxt:]
        init = init[:idx_nxt]
        break
    else:
        init.append(nxt)

idx = (k-len(init))%len(loop)
print(loop[idx])

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline

def ma():
    return map(int,input().split())
def main():
    n,k=ma()
    A=list(ma())
    ans=[0]*(n+1)
    now=1
    while True:
        ans[now]=1
        now=A[now-1]
        if ans[now]==1:
            use=ans.index(now)
            tool=len(ans)-use
            break 

    if use>=k:
        print(ans[k])
        exit()
    else:
        p=(k-use)%tool
        print(ans[use+p])

main()

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
flag = True
went = {1}
go = [1]
i = 0
while flag:
  if a[i] not in went:
    go.append(a[i])
    went.add(a[i])
    i = a[i]-1
  else:
    flag = False
loop = go[go.index(a[i]):]
if len(go) >= k:
  print(go[k])
else:
  k -= len(go)-len(loop)
  ans = k % len(loop)
  print(loop[ans])

Submission status: Runtime Error

Solution code:
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]


n, k = sp()
arr = l()
answer = [1]
s = {1}
index = 1
while True:
    temp = arr[answer[-1]-1]
    if temp in s:
        index = temp
        break
    s.add(temp)
    answer.append(temp)
if k <= len(answer)-1:
    out(answer[k-1])
    exit()
# print(answer)
k -= (len(answer)-1)
temp = answer.index(index)
answer = answer[index:]
# print(k)
k %= len(answer)-1
if k == 0:
    k = len(answer)
print(answer[k-1])

Submission status: Runtime Error

Solution code:
import sys
import math
import fractions
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(10**7)

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

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

visited = set()
visited.add(0)
trace = []
cur = 0
while True:
    trace.append(cur)
    if A[cur] in visited:
        cur = A[cur]
        break
    visited.add(A[cur])
    cur = A[cur]

pre = 0
for i, a in enumerate(trace):
    if a == cur:
        pre = i

loop = N - pre - 1

if K < pre:
    ans = trace[K - 1] + 1
else:
    r = (K - pre) % loop
    ans = trace[pre::][r] + 1

print(ans)

Submission status: Runtime Error

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

counter = 0
city = 1
tf = 0
list_city = [1]

while tf == 0 and counter < k:
    temp = A[city-1]
    city = temp
    if city in list_city:
        tf = 1
    else:
        list_city.append(temp)
        counter+=1

if tf == 1:
    print(list_city[k%(counter-list_city.index(city))+1])
else:
    print(city)

Submission status: Runtime Error

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

t = K%N

for i in range(t):
    if t==1:
  	    k = A[A[N-1]-1]
    else:
        k = A[k-1]
print(A[k-1])

Submission status: Runtime Error

Solution code:
def dfs(num,lis,count,target):
    visited[num]=count
    n_city=A[num]
    if visited[n_city]!=-1:
        lis.append(num)
        if target<=count:
              print(lis[target]+1)
        else:
            rep=len(lis)-visited[n_city]
            target-=visited[n_city]
            amari=target%rep
            temp=lis[visited[n_city]:]
            print(temp[amari]+1)
        exit()
    else:
        dfs(n_city,lis+[num],count+1,target)
    

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

visited=[-1]*N

dfs(0,[],0,K)

Submission status: Runtime Error

Solution code:
def main():
    import sys
    N,K=list(map(int,sys.stdin.readline().split()))
    A=list(map(int,sys.stdin.readline().split()))
    A=[1]+A
    route=[1]
    st=set()
    st.add(1)
    now=1
    while True:
        now=A[now]
        if now in st:
            break
        route.append(now)
        st.add(now)
    
    idx=route.index(now)
    if K-idx+1>0:
        if len(route)-1!=idx:
            print(route[idx-1+(K-idx+1)%(len(route)-idx)])
            if idx==0:
                raise Exception
            return
        else:
            print(route[-1])
    else:
        print(route[K])
    

main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = [-1]+a
v = [-1 for _ in range(n+1)]
v[1] = 0
x = a[1]
c = 0
while k > 0 and v[x] < 0:
    y = a[x]
    v[y] = v[x]+1
    x = y
    k -= 1
    c += 1

if k==0:
    print(x)
else:
    z = c - v[x]
    if z != 0:
        k = k%z
    else:
        k = k%c
    while k > 0:
        k -= 1
        x = a[x]
    print(x)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
dir = a[0]
hash_a = [False for _ in range(n)]
hash_a[0] = True
cnt = 0
while True:
    k -= 1
    if k == 0:
        break
    dir = a[dir - 1]
    if not hash_a[dir - 1]:
        hash_a[dir - 1] = True
    else:
        k %= cnt
    cnt += 1
print(dir)

Submission status: Runtime Error

Solution code:
# @author 

import sys

class DTeleporter:
    def solve(self, tc=0):
        n, k = [int(_) for _ in input().split()]
        a = [int(_) - 1 for _ in input().split()]
        done = dict()
        cur = 0
        steps = 0
        while cur not in done and steps < k:
            done[cur] = steps
            cur = a[cur]
            steps += 1

        d = steps - done[cur]
        steps = steps + ((k - steps) // d) * d

        while steps < k:
            cur = a[cur]
            steps += 1

        print(cur + 1)


solver = DTeleporter()
input = sys.stdin.readline

solver.solve()

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = [0]+list(map(int,input().split()))
b = [0]*(n+1)
cnt = 0
temp = 1
rep = 0
while 1:
    cnt += 1
    if b[temp] == 0:
        b[temp] = cnt
    else:
        rep = cnt-b[temp]
        # print(rep,cnt-1,b[temp])
        # print(b)
        break
    temp = a[temp]
# print((k-b[temp]+1) % rep)
if (k-b[temp]+1) >= 0:
    for i in range((k-b[temp]+1) % rep):
        temp = a[temp]
    print(temp)
    exit()
else:
    temp = 1
    for i in k:
        temp = a[temp]
    print(temp)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
p=1
l=[0]*n
if k<=100000:
    for i in range(k):
        p=A[p-1]
        l[p-1]+=1
    print(p)
    exit()
else:
    for i in range(100001):
        p=A[p-1]
        l[p-1]+=1
        if l[p-1]==2:
            x=i
            break
    d=1
    for j in range(100001):
        d=A[d-1]
        if d==p:
            y=j
            break
    z=(k-y-1)%(y-x)
    for i in range(z):
        p=A[p-1]
    print(p)

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

d = defaultdict(list)

p = 1
root = [p]

s, e = 0, 0

for i in range(K):
    d[p].append(i)
    if len(d[p]) == 2:
        s = d[p][0]
        e = i
        break
    root.append(A[p - 1])
    p = A[p - 1]
#print(s, e)

#print(root)

n = (K - s) % (e - s)
print(root[s + n])

Submission status: Runtime Error

Solution code:
def read_int():
    return int(input())

def read_int_map():
    return map(int,input().split(' '))

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

def read_s_list_loop(n):
    return [input() for _ in range(n)]

N,K = read_int_map()
An = read_int_list()
memo = [0]*(N+1)
memo_indx = [0]*(N+1)
memo[1] = 1
memo_indx[1] = 0
seq_an = [1]
next_place = An[0]
for i in range(len(An)):
    if memo[next_place] == 0:
        seq_an.append(next_place)
        memo[next_place] = 1
        memo_indx[next_place] = i + 1
        next_place = An[next_place-1]
    else:
        break
loop_idx = memo_indx[next_place]
loop_list = seq_an[loop_idx:]
if K <= len(seq_an):
    print(seq_an[K])
else:
    num = (K - len(seq_an)) % len(loop_list)
    print(loop_list[num])

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
As = list(map(int, input().split()))

history = {}
cycle = []
pos = 1
isEnd = False
for i in range(2*N):
    if pos in history:
        for j in range(len(cycle)):
            if cycle[j] == pos:
                head = cycle[:j]
                cycle = cycle[j:]
                isEnd = True
                break

    if isEnd:
        break

    history[pos] = 1
    cycle.append(pos)
    pos = As[pos-1]


#print(cycle)

if K <= len(head):
    print(head[K])
else:
    mod = (K-len(head)) % len(cycle)
    print(cycle[mod])

Submission status: Runtime Error

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

aList = list(map(int, input().split()))
seen = []
counter = 0
tsugi = 0
for i in range(k):
  tsugi = aList[tsugi]-1
  if tsugi not in seen:
    seen.append(tsugi)
  else:
    index = seen.index(tsugi)
    junkan = i-index
    break

for i in range((k-index)%junkan):
  tsugi = aList[tsugi]-1
print(aList.index(tsugi+1)+1)

Submission status: Runtime Error

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

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

now = 1

d = []

while True:
    if A[now-1] in d:
        i = d.index(A[now-1])
        check = d[i:]
        break
    d.append(A[now-1])
    now = A[now-1]
    print(d,now)

if K <= len(d):
    print(d[K-1])
else:
    K -= (len(d)-len(check))
    K = K % len(check)
    print(check[K-1])

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

loop = [0]
town = 0
visited = defaultdict(lambda: None)
visited[town] = 0

for i in range(1, k):
    town = a[town]
    if visited[town] != None:
        offset = visited[town]
        period = i - offset 
        break
    else:
        loop.append(town)
        visited[town] = i

print(loop[offset+((k-offset)%period)]+1)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10000000)
N,K = [int(v) for v in input().split()]
A = [int(v) for v in input().split()]
print(N,K)


loop = []

def dfs(now):
    loop.append(now)
    if A[now-1] == 1:
        return
    else:
        dfs(A[now-1])
dfs(1)

print(loop[K%len(loop)])

Submission status: Runtime Error

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

A = list(map(int,input().split()))
t = 0
c = 0
ans = [0] * n
L = []
for _ in range(k):
    if ans[t] == 1:
        t += k%c
        t %= n-1
        t = L[t]
        break
    else:
        ans[t] = 1
        L.append(t)
        t = A[t]-1
        c += 1
print(t+1)

Submission status: Runtime Error

Solution code:
import sys

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

array = [-1] * (n+1)
array[1] = 0

li = []
li.append(1)

tmp = -1
i = 1
index = 0
while True:
  if array[a[index]] != -1:
    tmp = array[a[index]]
    break
    
  if i == k:
    print(a[index])
    sys.exit(0)
    
  li.append(a[index])
  array[index] = i
  index = a[index] -1
  i += 1
  
  

k -= tmp
d = len(li)

k %= d

print(li[k+tmp])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = [-1]+a
v = [-1 for _ in range(n+1)]
v[1] = 0
x = a[1]
c = 0
while k > 0 and v[x] < 0:
    y = a[x]
    v[y] = v[x]+1
    x = y
    k -= 1
    c += 1

if k==0:
    print(x)
else:
    z = c - v[x]
    k = k%z
    while k > 1:
        k -= 1
        x = a[x]
    print(x)

Submission status: Runtime Error

Solution code:
N,K = map(int, input().split())
*A, = map(int, input().split())

seen = [False]*N
seen[0] = True
l = 0
root = []
for i in range(N):
    if seen[A[i]-1]==True:
        break
    l = l + 1
    seen[A[i]-1] = True
    root.append(A[i]-1)
print(root[K%l]+1)

Submission status: Runtime Error

Solution code:
def main():
  N, K = map(int, input().split())
  A = list(map(int, input().split()))
  ls = [1]
  loop = []
  tmp = 1
  for i in range(K):
    tmp = A[tmp-1]
    if tmp in ls:
      loop = ls[ls.index(tmp):]
      break
    ls.append(tmp)
  if K > len(ls):
    print(loop[(K-len(ls)+len(loop))%len(loop)])
  else:
    print(ls[K])
  
if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n , k = map(int , input().split())
arr = list(map(int , input().split()))
dic = defaultdict(int)
for i in range(1,n+1):
	dic[i] = arr[i-1]
cycle = []
def dfs(node):
	if node in cycle:
		return node
	else:
		cycle.append(node)
		k = dfs(dic[node])
	return k
cyind = dfs(1)
#print(cycle, cyind)
csize = len(arr[cyind:])
k -= cyind - 1
k %= csize
count = 0
curr = 1
#print("k " , k)
while count != k:
	curr = dic[curr]
	count+=1
print(curr)

Submission status: Runtime Error

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

n, k = na()
a = na()

proc = [0] * n
def rec(i, cnt):
    if proc[i]:
        return (cnt, i)
    proc[i] = 1
    return rec(a[i] - 1, cnt + 1)

def rec2(i, arr):
    if proc[i] >= 2:
        return arr
    proc[i] += 1
    arr.append(i)
    return rec2(a[i] - 1, arr)

cnt, i = rec(0, 0)
arr = rec2(i, [])

k -= cnt - len(arr)
print(arr[k % len(arr)] + 1)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=[0]+[int(j) for j in input().split()]
l=[-1]*(n+1)
ll=[]
i=1
idx=0
while True:
    if l[i]==-1:
        l[i]=idx
    else:
        ll.append(i)
        break
    ll.append(i)
    i=a[i]
    idx+=1

p=ll[-1]
nl=ll[p:-1]
print(nl[((k-l[p]+1)%(len(ll)-l[p]-1))-1])

Submission status: Runtime Error

Solution code:
import sys

readline = sys.stdin.readline
n, k = map(int, readline().split())
A = list(map(int, readline().split()))

visited = [False] * n
visited[0] = True
l = [1]
while True:
    x = A[l[-1]-1]
    if visited[x-1]:
        break
    l.append(x)
    visited[x-1] = True
# print(x)
print(l[x-1:][(k-l.index(x)) % len(l[x-1:])])

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, k = map(int, readline().split())
a = list(map(int, readline().split()))
roop = 0
dict = [False] * n
now = a[0]
for i in range(n + 1):
    if i + 1 == k:
        print(a[now - 1])
        exit()
    now = a[now - 1]
    if dict[now - 1]:
        k -= (i + 1)
        dict = [False] * n
        dict[now - 1] = True
        check = a[now - 1]
        for j in range(n + 1):
            print(dict)
            now = a[now - 1]
            if dict[now - 1]:
                k %= (j + 1)
                k += 1
                break
            else:
                dict[now - 1] = True
        break
    else:
        dict[now - 1] = True
now = check
for i in range(k):
    now = a[now - 1]
print(now)