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
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce


def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


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


def ZIP(n): return zip(*(MAP() for _ in range(n)))


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


def main():
    N, K = MAP()
    A = LIST()
    po = 1
    lis = [1]
    ct = defaultdict(int)
    ct[1] += 1
    for i in range(N-1):
        po = A[po-1]
        ct[po] += 1
        if ct[po] > 1:
            break
        lis.append(po)

    ind = lis.index(po)
    lis = lis[po:]
    # print(lis)
    # print(ind)

    K -= ind
    K %= len(lis)

    print(lis[K])


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

temp=1
trace=[1]
for i in range(K):
  temp=A[temp-1]
  if temp in trace:
    #print(temp)
    #print(trace.index(temp))
    start=trace.index(temp)
    circle=trace[start:]
    #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:
def main():
    from builtins import int, map, list, print, len
    import sys
    sys.setrecursionlimit(10 ** 6)

    input = sys.stdin.readline
    input_list = (lambda: input().rstrip().split())
    input_number = (lambda: int(input()))
    input_number_list = (lambda: list(map(int, input_list())))

    N,K= input_number_list()
    A = input_number_list()
    route = [1]
    now = 1
    is_looop = False
    try:
        for i in range(N):
            if A[i+1] in route:
                is_looop = True
                break
            now = A[now-1]
            route.append(now)
    except Exception:
        pass
    if is_looop and len(route) < K:
        start = A[now-1]
        start_idx = route.index(start)
        l_count = start_idx
        r_count = len(route) - start_idx
        K -= l_count
        m = K % r_count
        print(route[start_idx + m])
    else:
        print(now)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

def dfs(pos, depth):
    # 初めての訪問なら
    if dp[pos][0] == 0:
        dp[pos][0] = depth
        for i in dist[pos]:
            dfs(i, depth + 1)
    elif dp[pos][1] == 0:
        dp[pos][1] = depth
        for i in dist[pos]:
            dfs(i, depth + 1)
dfs(0, 0)
for i in range(N):
    if dp[i][0] == K or dp[i][1] == K:
        print(i + 1)
        break
    else:
        split = dp[i][1] - dp[i][0]
        if split > 0:
            if (K - dp[i][0]) % split == 0:
                print(i + 1)
                break

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(input().split())
K = K % N
pos = 0
for i in range(0, K):
    pos = int(A[pos])
print(pos+1)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
cnt=0
i=0
q=[1]
while True:
    q.append(a[i])
    if q.count(a[i])==2  :
        break
    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
    else:
        k-=len(q[:l])
    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(map(int,input().split()))
ischecked=[0]*N
move=[]
move1=[]
now=0
count=0
count1=0
while 1:
    move.append(now+1)
    nex=A[now]-1
    ischecked[now]=1
    if ischecked[nex]==1:
        roop=nex+1
        break
    now=nex
for i in range(len(move))[::-1]:
    move1.append(move[i])
    if move[i]==roop:
        b=len(move)-i
        break
if K>len(move):
    n=K-len(move)
    n=n%len(move1)
    print(move1[len(move1)-1-n])
else:
    print(move[K])

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
L = list(map(int,input().split()))
L2 = []

t = 1
r = 0
i = 0
c = 0
for i in range(k):
    #print(L2)
    t = L[t-1]
    if ｔ in L2:
        i = L2.index(t)
        r = len(L2) - i
        break
    else:
        L2.append(t)
#print(r)
#print(i)

k = (k - i)%r
#print(k)
print(L2[i+k-1])

Submission status: Runtime Error

Solution code:
def DFS(num):
    global time
    if D[num]==0:
        D[num]=time
        time +=1
    for i in M[num]:
        if color[i]=="white":
            color[num]="gray"
            color[i]="gray"
            DFS(i)
        elif color[i]=="gray":
            color[num]="black"
            color[i]="black"
            DFS(i)
        elif color[i]=="black":
            return


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

B=[]
point,cnt=0,0
while cnt<n*2:
    point=A[point]
    B.append(point)
    point -=1
    cnt +=1

M=[set() for _ in range(n+1)]
for i in range(len(B)-1):
    a,b=B[i],B[i+1]
    M[a].add(b)

time=1
color=["white" for _ in range(n+1)]
D=[0 for _ in range(n+1)]
DFS(A[0])
route=[]
for i in range(n+1):
    if color[i]=="black":
        route.append([D[i],i])

C=[]
for i in sorted(route):
    C.append(i[1])

k=k-D[C[0]]+1
print(C[k%len(C)-1])

Submission status: Runtime Error

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

a=input().split()

l=len(a)

for i in range(0,l):
    a[i]=int(a[i])

p=1
h=[]
go=0
i=0
while(go==0):
    i+=1
    
    

    h.append(p)
    p=a[p-1]
    if i==k:
        break
    if p in h:
        l=len(h)
        for j in range(0,l):
            if h[j]==p:
                amari=(k-i-1)%(i-j)
                p=h[j+amari+1]
                go=1
                break



print(p)

Submission status: Runtime Error

Solution code:
N,K = list(map(int, input().split()))
A = list(map(int, input().split()))
c = [0]*N

idx = 0
stp = 0
while(True):
  stp += 1
  idx = A[idx] - 1
  if c[idx]==0 and idx!=0:
    c[idx] = stp
  else:
    tmp1 = c[idx]
    tmp2 = stp - tmp1
    break
  if stp>=K:
    break

k1 = K - tmp1
k2 = k1%tmp2

for _ in range(k2):
  idx = A[idx] - 1
print(idx+1)

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

li = [0]
li.extend(list(map(int, input().split())))

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

tuita = [0]*(n+1)
cnt = 0
town = 1

while True:
  town = li[town]
  cnt += 1
  if tuita[town] == 0:
    tuita[town] = cnt
  else:
    if k < tuita[town]:
      print(search(1, li, k))
    elif k == tuita[town]:
      print(town)
    else:
      print(search(town, li, (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()))

now = 1
nowlist = [1]

for i in range(K):
    if nowlist.count(A[now-1]) == 0:
        now = A[now-1]
        nowlist.append(now)

    else:
        p = len(nowlist) - nowlist.index(A[now-1])
        break

mae = nowlist.index(A[now-1])
Q = (K-mae) % p
print(nowlist[Q + mae])


#print(now)
#print(nowlist)
#print(p)
#print(mae)

Submission status: Runtime Error

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


arr = []
location = 1
dif = 0
for i in range(len(towns)):
    if towns[location-1] not in arr:
        arr.append(towns[location-1])
        location = towns[location-1]
    else:
        index = arr.index(location-1)
        dif = index
        arr = arr[index:]
        break

index = (k + dif) % len(arr)
print(arr[index])

Submission status: Runtime Error

Solution code:
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

n,k = iim()
A = iil()
d = {0:True}
l = [0]
def move(num):
    l.append(A[num]-1)
    if d.get(A[num]-1,False):
        return True if A[num]-1 == 0 else False
    else:
        d[A[num]-1] = True
        return move(A[num]-1)

if move(0):
    rep = len(l)-1
    ini = 0
else:
    ini = l.index(l[-1])
    rep = len(l)-ini-1
if k <= ini:
    print(l[k]+1)
else:
    mod = (k-ini)%rep
    if mod == 0:
        mod = rep
#    print(l,mod,rep,ini)
    print(l[ini+mod]+1)

Submission status: Runtime Error

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

TeList = list(map(int, input().split()))
Tmp = 0
TmpList = [0]

ResultList = []
for _ in range(K):
    Tmp = TeList[Tmp]  - 1
    if Tmp in TmpList:
        ResultList = TmpList[TmpList.index(Tmp):]
        break
    else:
        TmpList.append(Tmp)

FirstStep = len(TmpList) - len(ResultList)

if K < len(ResultList):
    print(TmpList[K] + 1)
else:
    print(ResultList[(K - FirstStep) % len(ResultList)] + 1)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
# from collections import Counter
# from functools import *

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

n,k=LI()
a=LI()
b=[1]
visited=[-1]*n
visited[0]=0
# print(visited)

for i in range(k):
    # print(visited)
    nxt=a[b[-1]-1]
    b.append(nxt)
    if visited[nxt-1]==-1:
        visited[nxt-1]=i+1
    else:
        mod=(visited[nxt-1],i+1)
        break
    
# print(visited,b,mod)

ml,mr=mod
shuuki=mr-ml
k=k%shuuki+shuuki
# print(k)

now=1
for i in range(k):
    now=a[now-1]
print(now)

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
for i in range(n):
    li.append(A[next])
    next = A[next]-1

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


tmp = k%len(li[t:]) - len(li[0:t])

g=li[t:]
print(g[tmp])

Submission status: Runtime Error

Solution code:
def teleport(n, k, a):
  start = 1
  done = []
  p = k
  for i in range(k):
    done.append(start)
    start = a[start-1]
    if(start in done):
      ind = done.index(start)
      break
  dif = ind
  p-=dif
  p = p%(len(done)-dif)
  #print(p, dif, ind)
  return done[ind+p]

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

Submission status: Runtime Error

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

d = 1
b = [d]

for i in range(k):
    d = a[d-1]
    if b[0]==dn:
        break
    else:
        b.append(d)
 
print(b[k%len(b)])

Submission status: Runtime Error

Solution code:
# N, K = 4, 5
# ARR = [3, 2, 4, 1]

# N, K = 6, 727202214173249351
# ARR = [6, 5, 2, 5, 3, 2]


N,K = map(int,input().split())
ARR = list(map(int,input().split()))
NodeStatus = [False] * N
NodeFirstSteps = [0] * N
L = 0
OrderARR = []


def dfs(pos, arr, step):
    if NodeStatus[pos] == True:
        L = (step - NodeFirstSteps[pos])
        print(OrderARR[K % L] + 1)
        return
    OrderARR.append(pos)
    NodeStatus[pos] = True
    NodeFirstSteps[pos] = step
    dfs(arr[pos] - 1, arr, step + 1)


dfs(0, ARR, 0)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import sys

import math
input = sys.stdin.readline

N,M = map(int,input().split())
huga = list(map(int, input().split()))
l = [0] * N
loop = 0
mm = 0

if M >= N:
  x = huga[0] 
  for i  in range(1,M):
    x = huga[x-1] 
    if l[x-1] == 0:
        l[x-1] = i
    else:
        loopturm = i - l[x-1]
        loopend = i
        break

M =  ((M - loopend) % loopturm )+1
x = huga[0] 
for i  in range(1,M):
  x = huga[x-1] 
print (x)

Submission status: Runtime Error

Solution code:
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 = [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
for i in range(K):
  v = l.pop(0)
  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:
def Teleport(i,P):
    if(i==K):
        return print(P)
    else:
        Teleport(i+1,T[P-1])


N,K=(int(x) for x in input().split())
T=list((int(x) for x in input().split()))
Teleport(1,T[0])

Submission status: Runtime Error

Solution code:
def main():
    N, K = map(int, input().split())
    A = [int(x) for x in input().split()]
    L=[1]
    a = A[0]
    for _ in range(N-1):
        L.append(a)
        a=A[a-1]
        if a==1:
            g=K%len(L)
            print(l[g])
            break
        if a in L:
            x = L.index(a)
            g = (K-x )%(len(L)-x)
            print(L[x:][g])
            break
    
main()

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
lst=list(map(int,input().split()))
ans=1
count=0
a=[]
a.append(1)
for i in range(k):
  ans=lst[ans-1]
  count+=1
  if ans in a:
    break
  else:
    a.append(ans)
k-=count
ind=a.index(ans)
dif=count-ind
b=a[ind:]
print(b[k%dif])

Submission status: Runtime Error

Solution code:
# from itertools import combinations_with_replacement as comb

# n, m, x = map(int, input().split())
# for i in range(n):
#     ca = list(map(int, input().split()))

# ans = 20 * 10**5

# for i in range(n):
#     isOK = True
#     for j in range(1,m+1):
#         if ca[i][j] < x:
#             isOK = False
#             break
#     if isOK:
#         ans = min(ans, ca[i][0])

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] - 1)
        break
    cnt2[nxt] = i
    t.append(nxt)
    nxt = a[nxt]

K = (k-modC)//loop
modK = (k-modC)%loop
# print("-------")
# print(t)
# print("modC: " + str(modC))
# print("K: " + str(K))
# 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 = list(map(int, input().split()))
a_list = list(map(int, input().split()))

START = 1
# 訪れたタイミング
town_with_i = {START: 0}
# 現在地
current = START
# 既に訪れたことある街(巡回の判定に使う)
known_towns = set([START])
i = 0
for _ in range(k):
    i += 1
    # 現在地
    current = a_list[current - 1]

    # 既に来たことがあるということは巡回している
    if current in known_towns:
        break

    # メモ
    town_with_i[current] = i
    known_towns.add(current)

# 巡回までのステップ数
first_step = town_with_i[current]
# 1周するのに必要なステップ数
r = i - town_with_i[current]

# print(town_with_i)
# print(current)
# print(i)
# print(r)

loop_num = (k - first_step) % r

for i in range(loop_num):
    current = a_list[current - 1]

print(current)

Submission status: Runtime Error

Solution code:
N , K = map(int,input().split())
B = {}
C = {}
D = {0}
A = list(map(int,input().split()))
place = 0
num = 0
C[0] = 0
while True:
    place = int(A[place]) - 1
    num += 1   
    if place in D:
        Y = int(num) - int(C[place])
        break
    else:
        B[num] = place
        C[place] = num
        D.add(place)
if Y == 0:
    print(1)
else:
    X = (K - num) % Y
    print(B[int(C[place]) + X] + 1)

Submission status: Runtime Error

Solution code:
def function(arg1, arg2):
    N,K = map(int, arg1.split())
    teleportes = list(map(int, arg2.split()))
    checked = [0] * len(teleportes) # 訪れた街にチェック

    i = 0
    c = 1
    while True :
        nextTerminal = teleportes[i] - 1
        if checked[i] == 0:
            checked[i] = c # 何番目に訪れたか
            i = nextTerminal
            c += 1
        else:
            loops = c - checked[i] # 以前訪れてから何回旅したか
            
            break
    
    if K <= i:
        goal = teleportes[K]
    else:
        k = 0
        nextTerminal = 0
        while k in range((K-i)%loops + i):
            nextTerminal = teleportes[nextTerminal] - 1
            goal = nextTerminal + 1
            k+=1
    return str(goal)

if __name__ == '__main__':
    print(function(input(),input()))

Submission status: Runtime Error

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

A = list(map(int,input().split()))
visited = [1]
visited_list = [0]*N
visited_list[0] = 1
k = 0
l = 0
kaburi = 1
flag = True
def f(Ai):
    global k,l,visited,kaburi,flag
    # print("Ai",Ai,k)
    if k == K:
        flag = False
        print(Ai)
    elif visited_list[Ai-1] == 1 :
        kaburi = Ai
        k += 1
        l = k
    else:
        visited.append(Ai)
        visited_list[Ai-1] = 1
        k += 1
        f(A[Ai-1])

f(A[0])
if flag == True:
    hazime = visited.index(kaburi)
    b = visited[hazime:]
    print(b[(K-hazime)%(l-hazime)])

Submission status: Runtime Error

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

for i in range(n):
    tmp = i + 1
    if a[i] < tmp:
        k -= tmp
        loop = a[i]
        break

count = 0
li.append(loop)
while(True):
    li.append(a[loop-1])
    loop = a[loop-1]
    if loop == li[0]:
        break
del li[-1]
print(li)
buf = (k+1)%len(li)
print(li[buf])

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
visited = [False for _ in range(N)]

i = 1
c = 0
jun = []

if K <= N:
    while True:
        K -= 1
        i = A[i-1]
        if K == 0:
            print(i)
            exit()


while True:
    if i == A[i-1]:
        print(i)
        exit()
    if visited[i-1]:
        lp = i
        break
    else:
        visited[i - 1] = True
        jun.append(i)
        i = A[i-1]
        c += 1
ji = jun.index(lp)
K -= len(jun[:ji])
jun = jun[lp:]

kai = K % c

if kai == len(jun) + 1:
    print(jun[0])
else:
    print(jun[kai-1])

Submission status: Runtime Error

Solution code:
from collections import deque

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

r = deque(['1'])

fhinish_roop = 0
index = 0
while not fhinish_roop:
    if str(a[index]) not in r:
        r.append(str(a[index]))
        index = a[index] - 1
    else:
        fhinish_roop = 1
        r_2 = "".join(r)
# print(r, index)
roop_l = r_2.find(str(a[index]))
# print(roop_l)
roop_len = len(r) - roop_l
roop_start_index = roop_l
# print(roop_len)

if k < roop_start_index:
    print(a[k - 1])

else:
    ans = (k - roop_start_index) % roop_len
    # print('ans={}'.format(ans))
    print(r[roop_start_index + ans])

Submission status: Runtime Error

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

#ループする場合
flag=[0]*N
patt=[]
i=0
while True:
    patt.append(i)
    if flag[i]==1:
        #del patt[-1]
        break
    flag[i]=1
    i=A[i]-1

srt = patt.index(patt[-1])
#print(srt)
end = len(patt)-2
ptrn = patt[srt:end+1]

B = (K-srt) % len(ptrn)
if B==0:
    print(ptrn[0]+1)
else:
    print(ptrn[B+1])
    #print('0000000')

Submission status: Runtime Error

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

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=list(map(int,input().split()))

flag=[0]*n
place=[0]*n
p=0
for i in range(len(a_list)+1):
    if flag[p]:
        rep=i
        replis=place[p+1:i]
        st=p+1
        break
        
    else:
        place[i]=p+1
        flag[p]=1
        p=a_list[p]-1

print(replis[(k-st)%len(replis)])

Submission status: Runtime Error

Solution code:
def costCalc(index,cost):
    if costList[index] == -1:
        costList[index] = cost
        costCalc(a[index]-1,cost+1)

if __name__ == '__main__':
    n, k = map(int, input().split())
    a = [int(i) for i in input().split()]
    costList = [-1]*n
    costCalc(0,0)
    maxCount = max(costList)+1
    print(maxCount)

    k2 = k %maxCount
    print(costList.index(k2)+1)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
n, k, *a = map(int, open(0).read().split())
F = [0 for _ in range(n)]  # 来た？
T = [None for _ in range(n)]  # いつ来た？
def main(now, time, K):
    time += 1
    if F[now-1]:
        P = T[now-1]
        print(T.index(P + (K - time + 1) % (time - P)) + 1)
        exit()
    F[now-1] = 1
    T[now-1] = time
    main(a[now-1], time, K)

main(1, 0, k)

Submission status: Runtime Error

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

dist = A[0]
visited = {1}
_v = [1]
stop = 0
while True:
    if dist in visited:
        stop = dist
        break
    visited.add(dist)
    _v.append(dist)
    dist = A[dist-1]

made = 0
l = len(_v)
for i in range(l):
    if _v[i] == stop:
        break
    made += 1

loop = l - made
_v = _v[made:]

# print(stop)
# print(loop)
# print(made)
# print(_v)

if K <= made:
    print(_v[K])
else:
    K -= made
    K %= loop
    print(_v[K])

Submission status: Runtime Error

Solution code:
# coding:utf-8
from collections import defaultdict

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

for f, t in enumerate(A):
    to_next[f+1] = t

route = [1]
current_node = 1
loop_index = [-1, -1]

for idx, _ in enumerate(range(K)):
    route.append(to_next[current_node])
    current_node = route[-1]
    if len(route) != len(set(route)):
        loop_index[0] = route.index(current_node)
        loop_index[1] = idx
        break

# print(to_next)
# print(loop_index)
# print(route)

if loop_index[0] != 0:
    K = K - loop_index[0]
ans_idx = K % (loop_index[1] - loop_index[0] + 1)
# print(ans_idx)
print(route[loop_index[0]:loop_index[1]+1][ans_idx])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
t = list(map(int, input().split()))
str_g = 't[~-' * ~-k  + 't[0]' + ']' * ~-k 
print(eval(str_g))

Submission status: Runtime Error

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

k -= 1
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])
    break
  else:
    data[tmp-1] = i
    tmp = lst[tmp-1]


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

Submission status: Runtime Error

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

IN=lambda : map(int, input().split())
LIN=lambda : list(IN())
mod=1000000007

#+++++

def main():
	#a = int(input())
	n , k = IN()
	#s = input()
	al = LIN()
	pre_aa = [-1]*n
	pos = 0
	pre_aa[0]=0
	for i in range(1, k+1):
		pos = al[pos]-1
		if pre_aa[pos] >= 0:
			loop = i - pre_aa[pos]
			break
		pre_aa[pos] = i
	
	#pa((k,i,loop))
	for j in range((k- i)%loop):
		pos = al[pos]-1
	print(pos + 1)
	
	
	
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split(" "))
a = list(map(int,input().split(" ")))
here = 1
past = []
for x in range(1,k+1):
    here = a[here]
    past.append(here)
    for z in range(1,len(past)//2):
        if past[len(past)-z*2:len(past)-z]==past[len(past)-z:]:
            perm = past[len(past)-z:]
            print(perm[(k-x)%z])
            exit()
print(here)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = input().split()
A_MAP = {}
for i in range(N):
    A_MAP[str(i+1)] = A[i]

route_hash = {'1': 0}
current_pos = '1'
next_pos = ''
counter = 0
while counter <= K:
    next_pos = A_MAP[current_pos]
    counter+=1
    if next_pos in route_hash:
        break
    route_hash[next_pos] = counter # たどり着くまでにかかった回数
    current_pos = next_pos

remain = K - counter
counter -= route_hash[next_pos]
remain = remain % counter

current_pos = next_pos
for i in range(remain):
    next_pos = A_MAP[current_pos]
    route_hash[next_pos] = counter # たどり着くまでにかかった回数
    current_pos = next_pos
print(current_pos)

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
A = list(map(int, input().split()))
import collections
res = collections.deque('1')
rep = [0,0]
for i in range(n):
    print(res)
    if str(A[int(res[-1])-1]) not in res:
        res.append(str(A[int(res[-1])-1]))
    else:
        rep[0] = res.index(str(A[int(res[-1])-1]))
        rep[1] = len(res)
        break

#print(res)
#print(rep)
if k < len(res):
    print(res[k])
else:
    rep_num = rep[1] - rep[0]
    remainder = (k-rep[0])%rep_num
    print(res[rep[0] +remainder])

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
l = list(map(int,input().split()))
a = l[0] 
lis = [a]
for i in range(100):
    a = l[a-1]
    if a in lis:
        b = a
        break
    else:
        lis.append(a)

c = len(lis)
d = lis.index(b)
newlis = lis[d:c]
length = len(newlis)

t = k-d #最初のループを除く
s = t%length
answer = newlis[s-1]
print(answer)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
A = list(map(int, input().split()))
A = [-1] + A
memo = [1]
def func(i, town=1):
    global memo
    arrival = A[town]
    memo.append(arrival)
    if memo.count(arrival) == 2:
        return memo
    return func(i+1, A[town])

table = func(0, 1)
index = table.index(table[-1])
r = (k - index) % (len(table)-1 - index)
print(table[index+r])

Submission status: Runtime Error

Solution code:
tmp = input().split()
N = int(tmp[0])
K = int(tmp[1])

tmp = input().split()

Map = [0]*N
K = K%N
rt = [0]*K

for i in range(N):
    Map[i] = int(tmp[i])

def trip(self, steps):
    ntown = Map[self-1]
    if steps == K:
        return ntown
    rt[steps]=trip(ntown,steps+1)


    
Ft = trip(1,1)
print(rt[K-1])

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
    city=A[city]-1
    W.append(city)
    done[city]+=1

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

Submission status: Runtime Error

Solution code:
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
B = [0]
for i in range(N):
    p = A[B[i]]
    B.append(p-1)
i = 1
while i <=N+1:
    if B[i] in  B[0:i-1]:
        c = B[i]
        break
    i += 1
j = 0
d = 0
while j <= N:
    if B[j] == c and d > 0:
        e = j
        break
    if B[j] == c:
        d = j
    j +=1
if K <= e:
    print(B[K]+1)
else:
    f = (K-d) % (e-d)
    print(B[d+f]+1)

Submission status: Runtime Error

Solution code:
arr_1=input().split(" ")
n = int(arr_1[0])
k = int(arr_1[1])

towns = [int(o) for o in input().split(" ")]

history=list()
town=1

for i in range(1,k):
    if town in history:
        loop_start = history.index(town)
        loop_end = i - 1
        loop = history[loop_start:loop_end]

        m = k - loop_start
        if history[loop_start - 1 - 1] != history[loop_end - 1]:
            p = loop.pop(0)
            loop.append(p)
        
        a_index = m % len(loop) - 1
        print(loop[a_index])
        exit()

    history.append(town)
    town = towns[town-1]

print(town)

Submission status: Runtime Error

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