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:
n,k = map(int,input().split())
a = list(map(int,input().split()))
do = a[0]-1
ex = [0 for i in range(n+1)]
cntnum = [0 for i in range(n+1)]
cntnum [0] = 0
cntnum [do] = 1
ex[0] = 1
ex[do] = 1
cnt = 1
flag = 0
for i in range(k):
    do = a[do]-1
    if ex[do] == 1:
        cnt+=1
        ros = cnt - cntnum[do]
        aos = cntnum[do]-1
        if cntnum[do] == 0:
            aos = 0
            flag = 1
        break
    cnt += 1
    ex[do] = 1
    cntnum[do] = cnt

print(cnt,cntnum[do],k,aos,ros)

if k == ros:
    print(do+1)
    exit()


temp = (k - aos)%ros

if flag != 1:
    temp -= 1

ans = do

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

print(ans+1)

Submission status: Runtime Error

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

keiro = [1]
flag = True
now = 1
start = 0
loopN = 0
loop_list = []
not_loop = False
while flag:
    if A[now-1] in keiro:
        flag = False
        start = keiro.index(A[now-1])
        loopN = len(keiro[start:])
        loop_list = keiro[start:]
    else:
        keiro.append(A[now-1])
        now = A[now-1]
    if len(keiro) >= K:
        flag = False
        not_loop = True

if not_loop:
    print(keiro[K])
elif K - start >= 0:
    print(loop_list[(K - start) % loopN])
else:
    print(keiro[K])

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
loc=0
x=[-1]*N
y=0
distance=0
flag=False
for i in range(K+1):
  if(x[loc]>=0):
    distance=i-x[loc]
    y=x[loc]
    flag=True
    x[loc]=i
    break
  else:
    x[loc]=i
  loc=A[loc]-1
if(flag==True and y+distance<K):
  print(x.index((K-y)%distance+y)+1)
else:
  #print(x)
  print(x.index(K)+1)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

goal = a[0]
for i in range(k):
  goal = a[goal]
  print(goal)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
teleport = dict()
for i, a in enumerate(A):
    teleport[i+1] = a
# teleport

state = 1
connect = []
looplen= 0
for n in range(K):
    connect.append(state)
    state = teleport[state] 
    if state in connect:
        loop_init = connect.index(state)
        looplen = n-connect.index(state)+1   #0->0なら1
        #print(connect.index(state))
        #print(n)
        break
init
index = (k-init)%looplen
end = connect[index+init]
print(end)

Submission status: Runtime Error

Solution code:
from sys import stdin
def main():
    N, K = [int(x) for x in stdin.readline().rstrip().split()]
    A = [int(x) for x in stdin.readline().rstrip().split()]
    X = 1
    C = 0
    Log = [1]
    while C <= K:
        X = A[X-1]
        C += 1
        if (X in Log) == True:
            break
      
        Log += [X]
    
    K = (K - C)%(C - Log.index(X))

    print(Log[Log.index(X)+K])
    
main()

Submission status: Runtime Error

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

zyun = [a[0]]
alr = [False]*n
alr[0] = True
crr = a[0]

key = True

while key:
    if not alr[crr - 1]:
        alr[crr - 1] = True
        crr = a[crr - 1]
        zyun.append(crr)
        continue
    else:
        index = crr - 1
        key = False


# print(zyun, index)
if a.index(a[index]) == 0:
    zyun1 = zyun
    zyun2 = zyun
else:
    zyun1 = zyun[:a.index(a[index]) + 1]
    zyun2 = zyun[a.index(a[index]) + 1:]

# print(zyun1, zyun2)

if len(zyun1) >= k:
    print(zyun1[k])
else:
    ind = (k - len(zyun1)) % len(zyun2)
    if ind == 0:
        print(zyun2[-1])
    else:
        print(zyun2[ind - 1])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
lst = list(map(int, input().split()))
data = [-1]*100000

k -= 2
tmp = lst[0]
for i in range(1, k+1):
  #print(tmp, "t")
  if data[lst[tmp-1]-1] >= 1:
    num = (k - data[lst[tmp-1]-1])%(i-data[lst[tmp-1]-1])
    tmp = lst[tmp-1]
    break
  else:
    data[tmp-1] = i
    tmp = lst[tmp-1]


for j in range(num+1):
  #print(tmp)
  tmp = lst[tmp-1]
print(tmp)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
i=0
q=[1]
from collections import Counter
d=Counter()
d[1]=1
while True:
    q.append(a[i])
    if d[a[i]]==1:
        break
    else:
        d[a[i]]+=1
    i=a[i]-1
l=0
for i ,j in enumerate(q):
    if j==q[-1] :
        l=i
        break
if k>len(q[:l])+1:
    if q[-1]!=1:
        k-=len(q[:l])-1
    k%=len(q[l+1:])+1
    print(q[l+k+1])
else:
    print(q[k+1])

Submission status: Runtime Error

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

rireki = [0] * (n+1)
curr_c = 1
rireki[1] = 0
for i in range(k):
    next_c = a_list[curr_c-1]
    # print(i, curr_c, next_c)
    if next_c == 1:
        no_loop_count = 0
        loop_cnt = i + 1
        break
    elif rireki[next_c] == 0:
        rireki[next_c] = i+1
    else:
        # print(next_c)
        no_loop_count = rireki[next_c] -1
        loop_cnt = i - no_loop_count
        break
    curr_c = next_c

# print(rireki)

if k <= no_loop_count:
    ans = rireki.index(k)
else:
    # print('k',k)
    # print('no', no_loop_count)
    # print('lo', loop_cnt)
    ind = (k-1-no_loop_count)%loop_cnt +1
    rireki_fix = [i-no_loop_count for i in rireki]
    # print(ind, 'ind')
    ans = rireki_fix.index(ind)
    # print(rireki_fix)

print(ans)

Submission status: Runtime Error

Solution code:
def main():
    n,k = map(int,input().split())
    a = list(map(int,input().split()))
    ary = [0]
    tmp = [0] * n
    tmp[0] = 1
    now = 0
    for cnt in range(1,k+1):
        now = a[now] - 1
        ary.append(now)
        if cnt == k:
            print(now)
            return
        if tmp[now] != 0:
            break
        else:
            tmp[now] = cnt + 1
    m = (k - tmp[now]-1) % (cnt - tmp[now])
    print(ary[m+cnt-tmp[now] -1] + 1 )



if __name__=='__main__':
    main()

Submission status: Runtime Error

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

G = {}
for i in range(1, n + 1):
    G.update({i: a[i - 1]})

seen = [False] * (n + 1)
path = []

def dfs(graph, start):
    global return_ans
    seen[start] = True
    path.append(start)
    
    if seen[graph[start]]:
        return_ans = graph[start]
    else:
        dfs(graph, graph[start])
    
    return path, return_ans

line, point = dfs(G, 1)
long = len(line)
m = line.index(point)
l = long - m

print(line[(k - m) % l + m])

Submission status: Runtime Error

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

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

Submission status: Runtime Error

Solution code:
import sys
# sys.stdin = open('input.txt')

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

cycle = n + 1
sub = []
place = 0

for i in range(len(a)):
    place = a[i]
    sub.append(a[i])
    if place == 0:
        sub = sub[:-1]
        cycle = i
        break

# print(cycle, sub)
ans = sub[k%cycle] + 1
print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
done=[0 for _ in range(N)]
done[0]=1
W=[0]
loop=0
city=0

for i in range(N):
    if done[A[i]-1]==2:
        init=W.index(A[i]-1)
        loop=i-init
        break
    elif city==A[city]-1:
        init=i
        loop=1
        break
    city=A[city]-1
    W.append(city)
    done[city]+=1

if min(done)>0:
    init=0
    loop=N

print(W[(K-init)%loop+init]+1)

Submission status: Runtime Error

Solution code:
from sys import stdin
input = stdin.readline
def minus(n):
  return n-1
  
def main():
  num_list = list(map(int, input().split()))
  A = list(map(int, input().split()))
  N=num_list[0]
  K=num_list[1]
  A_i=0
  N_list=[0]*N
  A =list(map(minus, A))
  sFlag=True
  i=0
  while(sFlag):
    i=i+1
    pre=A_i
    N_list[A_i]+=1
    if(N_list[A_i]==3):
      sumA=N_list.count(int(2))
      K=(K-i)%sumA
      for j in range(K):
        pre=A_i
        te=A[A_i]
        A_i=te
      break
    te=A[A_i]
    A_i=te
    if(i>=K):
      sFlag=False
      break
  print(A_i+1)
  
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

stp = -1 
def main():
    n, k = map(int, readline().split())
    a = [int(i)-1 for i in readline().split()]

    order = []
    ex = set()
    def dfs(node):
        global stp
        order.append(node)
        ex.add(node)
        nx = a[node]
        if nx in ex:
            stp = nx
            return
        dfs(nx)
    dfs(0)
    cnt = order.index(stp)
    m = len(order[cnt:])
    idx = (k-cnt)%m
    print(order[cnt:][idx]+1)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
visited = [0] * n
f = True
visited[0] = 1
index = 0
memo = [0]
while f:
    index = a[index] - 1
    if visited[index]:
        v = a[index] - 1
        break
    memo.append(index)
    visited[index] = 1
f = False
list_ = []
for i in range(len(memo)):
    if not (f) and memo[i] == v:
        f = True
        list_.append(memo[i])
    if f:
        list_.append(memo[i])
if (k + 1) % len(list_) == 0:
    i = len(list_) - 1
else:
    i = (k + 1) % len(list_) - 1
print(memo[i] + 1)

Submission status: Runtime Error

Solution code:
from sys import stdin
def main():
    N, K = [int(x) for x in stdin.readline().rstrip().split()]
    A = [int(x) for x in stdin.readline().rstrip().split()]
    X = 1
    C = 0
    Log = [1]
    while C <= K:
        X = A[X-1]
        C += 1
        if (X in Log) == True:
            break
      
        Log += [X]
    
    K = (K - C)%(C - Log.index(X))
    print(Log[Log.index(X)+K])
    
main()

Submission status: Runtime Error

Solution code:
n, k = map( int, input().split() )
a = [ int( i ) for i in input().split() ]

leg = [ 0 ] * n
leg[ 0 ] = 1

p = 0
city_old = 1
for x in range( k ):
    city_new = a[ city_old-1 ]
    if leg[ city_new-1 ] == 0:
        leg[ city_new-1 ] += x + 1
    else:
        loop = x + 1 - leg[ city_new-1 ]
        modk = ( k - ( x + 1 ) ) % loop
        break
    city_old = city_new
    p += 1

if p == k:
    print( city_old )
    exit()


city_old = city_new
for x in range( modk ):
    city_new = a[ city_old-1 ]
    city_old = city_new

print( city_old )

Submission status: Runtime Error

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

L = []
now = 0

for i in range(K):
    if now in L:
        break
    else:
        L.append(now)
        now = A[now] - 1

if now == 0:
    Bl = L[:now]
    Br = L[now:]
else:
    Bl = L[:now+1]
    Br = L[now+1:]
cnt = len(Bl)
K -= cnt
idx = K % len(Br)

print(Br[idx]+1)

Submission status: Runtime Error

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

f = [0] * n
i = 0
x = 0
while True:
    f[i] = 1
    i = a[i] - 1
    x += 1
    if f[i]:
        break
    
f = [0] * n
cnt = 0
while True:
    f[i] = 1
    i = a[i] - 1
    cnt += 1
    if f[i]:
        break

ans = i
cnt -= x - cnt
if k < x - cnt:
    ans = 0
    for i in range(k):
        ans = a[ans] - 1
    print(ans + 1)
    exit()
    
else:
    for i in range((k - x + cnt) % cnt):
        ans = a[ans] - 1

print(ans + 1)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
A = [int(i) for i in input().split()]

Visit = [False for i in range(n+1)]

loop_st,loop_end,loop_len = 0,0,0
st = 1
releki = []
for i in range(1000000):
    
    if Visit[st] == True:
        loop_key = st
        loop_st = releki.index(loop_key)
        loop_end = len(releki)-loop_st
        loop_len = len(releki)-loop_st-1
        break
    releki.append(st)
    Visit[st] = True
    st = A[st-1]
k-= loop_st
print(releki[loop_len%k])

Submission status: Runtime Error

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

Submission status: Runtime Error

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

next=0
hoge=[]
zisyo={}
for i in range(k):
    next=A[next]
    if next in zisyo:
        t=next
        break
    else:
        zisyo[next]=1
        hoge.append(next)

for i in range(len(hoge)):
    if hoge[i]==t:
        hoge_1=hoge[:i]
        hoge_2=hoge[i:]

if k<=len(hoge_1):
    ans = 0
    for i in range(k):
        ans=A[ans]
else:
    k=k-len(hoge_1)-1
    k=k%len(hoge_2)
    ans=hoge_2[0]
    for i in range(k):
        ans=A[ans]


print(ans+1)

Submission status: Runtime Error

Solution code:
import math
def binary_search(list,target):

	result = -1
	left = 0
	right = len(list) - 1

	while left <= right:
		center = int((left + right)/2)
		if list[center] == target:
			result = center
			break
		elif list[center] < target:
			left = center + 1
		elif list[center] > target:
			right = center - 1

	if result == -1:
		return False
	else:
		return True

n,k=map(int,input().split())
a=list(map(int,input().split()))
i=0
pasta=[1]
while True:
    if binary_search(pasta,a[i]):
        roopy=pasta.index(a[i])
        roop=pasta[roopy:]
        break
    else:
        pasta.append(a[i])
        i=a[i]-1
if k>len(pasta):
    k-=len(pasta)
    k%=len(roop)
    print(roop[k])
else:
    print(pasta[k])

Submission status: Runtime Error

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

A_itta = [None] * N
# A_cycle = '1'

A_stayed = []
# A_stayed.append(1)

i = 0
while True:
    # 行ったことある
    if A_itta[i]:
        break

    # 訪問済みフラグ
    A_itta[i] = 1

    # 訪問順リスト
    A_stayed.append(i + 1)

    # 次の町のidx
    i = A[i] - 1

# print('ループするまでにいった町', A_stayed)

# 最初の町からループする場合
if i == 0:
    cycle = A_stayed
else:
    cycle = A_stayed[i+1:]
    K -= i+1

ans = cycle[K % len(cycle)]

# print('i', i)
# print('loop=', cycle)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, coo_matrix

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

value=np.ones(N)
row = np.array(range(N))
col = np.array(a)

A = coo_matrix((value,(row,col)))
A = csr_matrix(A)

A_k = A ** K
r, c = A_k.nonzero()

print(c[0]+1)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
B = []
B.append(A[0])
b = 0
c = 1
while True:
  b = A[c-1]
  c = A[b-1]
  B.append(c)
  if A[-1] == A[-2]:
    break
  if len(B) == len(A):
    break
print(B[k])

Submission status: Runtime Error

Solution code:
from copy import copy, deepcopy
from collections import Counter
from math import sqrt, floor, factorial
from itertools import permutations, combinations, combinations_with_replacement
from operator import mul
from functools import reduce
import bisect

MOD = 10**9 + 7
INF = float('inf')

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

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

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

mem = [0]*N
mem2 = [0]*N

idx = 0
count1 = 0
while True:
    mem[idx] += 1
    if mem[idx] == 2:
        break
    count1 += 1
    idx = A[idx]


idx2 = idx
count2 = 0

count2 += 1
idx2 = A[idx2]

while True:
    if idx2 == idx:
        break
    count2 += 1
    idx2 = A[idx2]

tmp = count1 - count2

if tmp >= K:
    for _ in range(K):
        idx = A[idx]
else:
    e = (K - tmp) % count2 + tmp
    ans = 0
    for _ in range(e):
        ans = A[ans]

print(ans+1)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
aa=[]
res=0
ans=0
q=0
for i in range(1,k+1):
    aa.append(res)
    res=a[res]-1
    if res in aa:
        m=res+1
        break
k=k-i
for i in range(1,k+1):
    res=a[res]-1
    if res==m-1:
        q=i
        break
k=k%q
for i in range(1,k+1):
    res=a[res]-1
print(res+1)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 20:50:56 2020
"""

import sys
#import numpy as np

sys.setrecursionlimit(10 ** 9)
#def input():
#    return sys.stdin.readline()[:-1]
mod = 10**9+7

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

city = [False for i in range(N)]
city[1-1] =True
now = 1

counta1 = 0
while True:
    counta1 += 1
    prev = now
    now = A[now-1]
    print(prev,now,counta1)
    if city[now-1]:
        break
    elif counta1 == K:
        print(now)
        sys.exit()
    else:
        city[now-1] = True

counta = 1
rout = []
rout.append(now)
while now != prev:
    now = A[now-1]
    rout.append(now)
    counta +=1
    print(now,rout,counta)

ans = rout[(K-counta1) % counta]
print(ans)

Submission status: Runtime Error

Solution code:
n,k=list(map(int,input().split()))
A=list(map(int,input().split()))
start,i=1,0
root=[1]

for j in range(k):
  start=A[start-1]
  if start in root:
    i = start
    break
  root.append(start)
  
if k <= len(root):
  print(root[k-1])
else:
  newroot=root[i-1:]
  print(newroot)
  ans=(k-len(root))%len(newroot)
  print(newroot[ans])

Submission status: Runtime Error

Solution code:
n,k = list(map(int,input().split()))
A = list(map(int,input().split()))
tour=[0]
next_town = 0
for i in range(n*2):
    next_town=A[next_town]-1
    if next_town in tour:
        first_roop_idx = tour.index(next_town)
        break
    tour.append(next_town)
#print(tour)
if k<=len(tour):
    ans = tour[k]
else:
    k-=first_roop_idx
    ans = tour[k%(len(tour)+first_roop_idx)+first_roop_idx-1]
print(ans)

Submission status: Runtime Error

Solution code:
n,k=list(map(int,input().split()))
arr=list(map(int,input().split()))
vis=[False for i in range(n)]
a=[]
start=curr=0
vis[0]=True
a.append(start)
for i in range(k):
    curr=a[-1]
    if vis[arr[curr]-1]:
        a.append(arr[curr] - 1)
        break
    else:
        vis[arr[curr]-1]=True
        a.append(arr[curr]-1)
#now i have req cycle
if a[0]==a[-1]:
    a.pop()
    print(a[k%(len(a))]+1)
else:
    count=0
    for i in range(len(a)):
        if a[i]==a[-1]:
            new =a[i:-1]
            break
        else:
            count+=1
            continue
    #print(len(new),new)
    print(new[(k-count)%(len(new))]+1)

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
P = [i -1 for i in map(int,input().split())]
ss = set([])
point = 0
for i in range(N):
    if point in ss:
        break
    ss.add(point)
    point = P[point]
S = [0]
points = 0
for i in range(len(ss)-1):
    points = P[points]
    S.append(points)
loop = S[S.index(point):]
ll = len(S)
l = len(loop)
if ll >= M:
    print(S[M]+1)
else:
    print(loop[(M-ll)%l]+1)

Submission status: Runtime Error

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

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

log = []

def func(x, iter):
    x = A[x-1]

    if iter+1 == K:
        return x
    if x in log:
        tmp = K%(iter+1)
        return log[tmp]
    else:
        log.append(x)
        iter += 1
        return func(x, iter)

print(func(1, 0))

Submission status: Runtime Error

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

Submission status: Runtime Error

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

from collections import deque 
tmp = 1
num = deque()
 
for i in range(N):
    num.append(tmp)
    if tmp == A[tmp-1]:
        judge = tmp
        flag1 = 1
        break
    tmp = A[tmp-1]
    if tmp in num:
        judge = tmp
        flag2 = 1
        break
print(num)

if flag2 == 1:
    print(num[(K-num.index(judge))%(len(num)-num.index(judge)) + num.index(judge)])
elif flag1 == 1:
    if K >= len(num):
        print(judge)
    else:
        print(num[K-1])

Submission status: Runtime Error

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

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

if n==0:
  print(1)
  exit()

nowT = 1
n = 0
nP = [1]
while True:
  nowT = A[nowT]
  n+=1
  if nowT in nP:
  	break
  if n==K:
    print(nowT)
    exit()
  nP.append(nowT)

pos = nP.index(nowT)

pat = len(nP)-pos

#print( nowT , nP)
#print( pos , pat )

print( nP[ (K-pos)%pat + pos ] )

Submission status: Runtime Error

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

li = [0]
li.extend(list(map(int, input().split())))
tuita = [0]*(n+1)
cnt = 0
town = 1

def search(town, times):
  global li
  if times <= 0:
    return town
  else:
    return search(li[town], times-1)

while True:
  town = li[town]
  cnt += 1
  if tuita[town] == 0:
    tuita[town] = cnt
  else:
    if k < tuita[town]:
      print(search(1, k))
    elif k == tuita[town]:
      print(town)
    else:
      print(search(town, (k - tuita[town]) % (cnt - tuita[town])))
    break

Submission status: Runtime Error

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

# print(a)
cnt = [0]*(10**5)
cnt2 = [0]*(10**5)#何回目に出てきたか
t = []
nxt = 0
loop = 0

for i in range(10**5):
    cnt[nxt] += 1
    if cnt[nxt] >= 2:
        # print("i: " + str(i))
        # print("nxt: " + str(nxt))
        loop = i - cnt2[nxt]
        modC = max(0, cnt2[nxt] - 2)
        break
    cnt2[nxt] = i
    t.append(nxt)
    nxt = a[nxt]

modK = (k-modC)%loop
# print("-------")
# print(t)
# print("modC: " + str(modC))
# print("modK: " + str(modK))
# print("loop: " + str(loop))
# print(modK)
# print(loop)
# print("-------")

print(t[modC + modK] + 1)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
visit = [False] * n
visit[0] = True
nx = a[0]
keiro = [1]
roop = 0
for i in range(k):
    if visit[nx-1] == False:
        visit[nx-1] = True
        keiro.append(nx)
    else:
        roop = nx
        break
    nx = a[nx-1]
if roop == 0:
    print(keiro[k-1])
else:
    basyo = keiro.index(roop)-1
    ix = (k-basyo) % len(keiro)

    print(keiro[2:][ix])

Submission status: Runtime Error

Solution code:
#import math
#=input()
#=int(input())
n,k=map(int,input().split())
a=list(map(int,input().split()))
#=[list(map(int,input().split())) for _ in range()]

q = a[0]
l = []
for i in range(k-1):
    if q in l:
        w = l.index(q)
        break
    l += [q]
    q = a[q-1]
f = len(l[:w])
ll = l[w:]
g = len(ll)
if k <= f:
    print(l[k - 1])
else:
    r = (k - f) % g - 1
    print(ll[r])

Submission status: Runtime Error

Solution code:
from sys import stdin

def main():

    input = stdin.readline

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

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

    itta_list = []
    idou_num = 0

    pos = 0

    for i in range(K):
        # itta_list記憶
        if pos not in itta_list:
            itta_list.append(pos)
        else:
            idou_num = i
            break

        # 次の街へ
        pos = A[pos] - 1

    roop_list = itta_list[itta_list.index(pos):]

    amari = (K - idou_num) % len(roop_list)

    ans_pos = roop_list[amari] + 1

    print(ans_pos)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n,k=list(map(int,input().split()))
A=list(map(int,input().split()))
start,i,j=1,0,0
root=[1]

for j in range(k):
  start=A[start-1]
  if start in root:
    i = start
    break
  root.append(start)
  
if k <= len(root):
  print(root[k-1])
else:
  newroot=root[i-1:]
  print(newroot)
  ans=(k-len(root))%len(newroot)
  print(newroot[ans])

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A_list = list(map(int, input().split()))
dic_A = {0:1}
direction = 0
for i in range(K):
    direction = A_list[direction]-1
    if direction in dic_A:
        dic_A[direction] += 1
        if dic_A[direction] >= 3:
            break
    else:
        dic_A[direction] = 1
cnt = 0
dic_ans = {}
for k, v in dic_A.items():
    if v >= 2:
        cnt += 1
        dic_ans[k] = 1
ans = K - (len(dic_A) - cnt)
ans %= cnt
for k, v in dic_ans.items():
    if ans == 0:
        true = k
        break
    ans -= 1
print(true+1)

Submission status: Runtime Error

Solution code:
n,k = list(map(int,input().split()))
A = list(map(int,input().split()))
tour=[0]
next_town = 0
for i in range(n*2):
    next_town=A[next_town]-1
    if next_town in tour:
        first_roop_idx = tour.index(next_town)
        break
    tour.append(next_town)
print(tour)
if k<=len(tour):
    ans = tour[k]
else:
    k-=first_roop_idx
    ans = tour[k%(len(tour)+first_roop_idx)+first_roop_idx-1]
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
next = 1
a = list(map(int, input().split()))
b = []
while True:
  b.append(next)
  next = a[next - 1]
  if next in b:
    break
for i in b:
  if i != next:
    b.pop(i)
  else:
    b.pop(i)
    break
count = len(b)
k = k % count
next = 1
for j in range(k):
  next = a[next - 1]
print(next)

Submission status: Runtime Error

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

f = [0] * n
i = 0
x = 0
while True:
    f[i] = 1
    i = a[i] - 1
    x += 1
    if f[i]:
        break
    
f = [0] * n
cnt = 0
while True:
    f[i] = 1
    i = a[i] - 1
    cnt += 1
    if f[i]:
        break

ans = i
cnt -= x - cnt
if k < x:
    ans = 0
    for i in range(k):
        ans = a[ans] - 1
    print(ans + 1)
    exit()
    
else:
    for i in range((k - x + cnt) % cnt):
        ans = a[ans] - 1

print(ans + 1)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
N,K = map(int,input().split())
A = [0] + list(map(int,input().split()))
G = dict([(i,[]) for i in range(1,N+1)])
for i in range(1,N+1):
  G[i].append(A[i])

l = deque([A[1]])
seen = [False for i in range(N+1)]
seen[1] = True
d = [0 for i in range(N+1)]
d[A[1]] = 1
if A[1] == 1:
  print(1)
  sys.exit()
  
for i in range(K):
  v = l.popleft()
  if seen[v] != True:
    seen[v] = True
    l.append(A[v])
    if seen[A[v]] == True: 
      a = d[A[v]]
      b = d[v] + 1 - a
    else:  
      d[A[v]] = d[v] + 1
  else:  
    start = v
    break

kaisu = (K-a)%b
p = start
for i in range(kaisu):
  p = A[p]
print(p)

Submission status: Runtime Error

Solution code:
n,k = [int(e) for e in input().split()]
a = [int(e) for e in input().split()]
tele = [1,a[0]]
def teleport(b,j):
    tele.append(a[b-1])
    if j >= n-2:
        return None
    teleport(a[b-1],j+1)
teleport(a[0],0)

ans = sorted(tele,key = tele.index)
same = 0
for i in range(n):
    if ans[i] == ans[i+1]:
        same = ans[i]
        break
index1 = -1
index2 = -1
for i in range(n+1):
    if tele[i] == same and index1 == -1:
        index1 = i
    elif tele[i] == same:
        index2 = i

res = tele[:index2]
if k < index1:
    print(res[k])
else:
    print(res[index1 + ((k-index1)%(index2-index1))])

Submission status: Runtime Error

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

def func1(lst, value):
    return [i for i, x in enumerate(lst) if x == value]
  
temp=1
trace=[1]
for i in range(K):
  temp=A[temp-1]
  ans=func1(trace,temp)
  if len(ans)==1:
    #print(temp)
    #print(trace.index(temp))
    #start=trace.index(temp)
    circle=trace[ans[0]:]
    #print(circle)
    break
  trace.append(temp)
  #print("temp",temp)
#print((K-i)%len(circle)-1)
amari=(K-i)%len(circle)-1
print(circle[amari])

Submission status: Runtime Error

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

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

reach = [-1 for i in range(N)]
reach[0] = 0 #最初の町は0回でいく
now = 0
#loop = 1
dic ={}
dic[0] = 0
for i in range(N+1):
  to = A[now]-1
  if reach[to] != -1:
    ini = i+1
    #print(i,to,reach[to])
    loop = i+1 - reach[to]
    break
  if i+1 not in dic:
    dic[i+1] = to
  reach[to] = i+1
  #loop += 1
  now = to


#print(dic,reach,loop,ini)
if K <= ini:
  print(dic[K]+1)
else:
  t = (ini-loop) + (K-ini)%loop
  print(dic[t]+1)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
List = list(map(int, input().split()))
Lists = []
Listss = []
a = 1
count = 0
counts = 0
while a != Lists:
  a = List[a]
  Lists.append("a")
  count = count+1
while count != Listss:
  a = List[a]
  Listss.appened("a")
  counts = counts+1
countss = (K - count) % counts 
for i in range(countss):
  a = List[a]
print(a)

Submission status: Runtime Error

Solution code:
from collections import deque
n,k=map(int, input().split())

A = deque(map(int, input().split()))
li = []
li.append(1)

next = 0
t=0
rep = False
for i in range(n):
    li.append(A[next])
    next = A[next]-1

    if A[next] in li:
        t = li.index(A[next])
        rep = True
        break


if rep == True:
    tmp = k%len(li[t:]) - len(li[0:t])
    g=li[t:]
    print(g[tmp])
else:
    print(li[k])

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

from pprint import pprint
from collections import deque, defaultdict
import itertools
import math
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.buffer.readline
INF = float('inf')

n_towns, k_times = map(int, input().split())
teleport = list(map(int, input().split()))

seq = []
flags = [False] * n_towns
visited = [0] * n_towns

flags[0] = True
seq.append(0)
visited[0] += 1

town_prev = 0

while True:
    town_next = teleport[town_prev] - 1
    visited[town_next] += 1
    if flags[town_next]:
        seq.append(town_next)
        break
    seq.append(town_next)
    flags[town_next] = True
    town_prev = town_next

loop_len = 0
for town, count in enumerate(visited):
    if count == 2:
        loop_idx = seq.index(town)
# print(loop_idx)

if k_times < loop_idx:
    print(seq[k_times])
else:
    arr = seq[loop_idx:len(seq) - 1]
    r = (k_times - loop_idx + 1) % (len(seq) - loop_idx)
    # print(arr, r)
    print(arr[r])