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: Wrong Answer

Solution code:
N,K = map(int,input().split())
a = list(map(int,input().split()))
list_a = []
list_b =[]
list_a.append(1)
for i in range(1,K+1):
  if i == 1:
    k = i
  if a[k-1] in list_b:
    break
  elif a[k-1] in list_a:
    list_b.append(a[k-1])
  if a[k-1] not in list_a:
    list_a.append(a[k-1])
  k = a[k-1]
count_a = len(list_a) 
count_b = len(list_b)
#print(list_a,list_b)
if count_b != 0:
  num_k = K-(count_a-count_b)
  num_k = num_k%count_b
  if 1 in list_b:
    list_b.insert(0,1)
  print(list_b[num_k])
elif count_b ==0:
  print(list_a[count_a-1])

Submission status: Wrong Answer

Solution code:

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

dp = [[0] * (N + 1) for _ in range(50)]
dp[0] = [0] + X
for k in range(1, 50):
    for i in range(N + 1):
        dp[k][i] = dp[k - 1][dp[k - 1][i]]

ans = 1
for k in range(50):
    if K >> k & 1:
        ans = dp[k][ans]

print(ans)

Submission status: Wrong Answer

Solution code:
#import time

def main():
    N, K = map(int, input().split())
    As = list(map(int, input().split()))
    As = [0]+As
    ikisaki = As[1]
    aru = {1}
    itta = [1]
    imaitta = 1
  
    while not ikisaki in aru:
        imaitta = ikisaki
        ikisaki = As[ikisaki]
        itta.append(imaitta)
        aru.add(imaitta)
    ind = itta.index(ikisaki)
    kurikaesi = itta[ind:]
    itidokiri = itta[:ind]
    ans = itidokiri[K] if K == 1 else kurikaesi[(K-len(itidokiri))%len(kurikaesi)]


    return ans

if __name__ == '__main__':
    #start = time.time()
    print(main())
    #elapsed_time = time.time() - start
    #print("経過時間:{}".format(elapsed_time * 1000) + "[msec]")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import bisect
import heapq
import itertools
import math
import numpy as np
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from math import gcd
from operator import add, itemgetter, mul, xor
def cmb(n,r,mod):
  bunshi=1
  bunbo=1
  for i in range(r):
    bunbo = bunbo*(i+1)%mod
    bunshi = bunshi*(n-i)%mod
  return (bunshi*pow(bunbo,mod-2,mod))%mod
mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]
n,k = MI()
a = LI()
#薫り高い町を求めよう
#訪れた町をリストに入れていって重複が出てきたらそこが薫り高い町
#そこまでのstep数も数える
cnt = 0
place=[1]
k = a[1-1]
for i in range(n):
    if a[k-1] in place:
        town = a[k-1]
        cnt = i - 1
        break
    place.append(a[k-1])
    k = a[k-1]
#周期を求める
t = 0
now = town
for i in range(n):
    t += 1
    now = a[now-1]
    if now == town:
        break
print(a[(k-cnt)%t+1])

Submission status: Wrong Answer

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

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

cheak = [0] * (2*(10**5) + 1)

point = 1

dev = [1]
flag = 0

for i in range(1, n+1):
    point = a[point]
    dev.append(point)
    if cheak[point] != 0:
        loop = i -cheak[point]
        pre_loop = cheak[point]
        flag = 1
        break
    else:
        cheak[point] = i

if flag:
    rest = (k - pre_loop) % loop
    for j in range(rest):
        point = a[point]
        dev.append(point)

print(point)

Submission status: Wrong Answer

Solution code:
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
a = [i-1 for i in a]
# print(a)
visit = [0]*(n+1)
v = []
v.append(0)
i = 0
num = 0
while True:
    if visit[a[v[i]]]==0:
        v.append(a[v[i]])
        visit[a[v[i]]] += 1
        i += 1
    else:
        num = len(v)
        v = v[v.index(a[v[i]]):]
        break
# print(v)
k -= num
# print(k%len(v))
print(v[k%len(v)]+1)

Submission status: Wrong Answer

Solution code:
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
a = [i-1 for i in a]
# print(a)
v = []
v.append(a[0])
num = 0
i = 0
while True:
    if (a[v[i]]!=v[0]) and (a[v[i]] not in v):
        v.append(a[v[i]])
        i += 1
    elif a[v[i]]!=v[0]:
        # print(v)
        num += len(v)
        b = a[v[i]]
        v = []
        v.append(b)
        i = 0
    else:
        break
# print(v)
k -= num
# print(k%len(v))
print(v[(k-1)%len(v)]+1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a_list = list(map(int, input().split()))
loop = []
now = 1
while not now in loop:
    loop.append(now)
    now = a_list[now - 1]
loop_start_index = loop.index(now)
print(loop[loop_start_index + (k - loop_start_index) % (len(loop) - loop_start_index)])

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(lambda x: x - 1, map(int, input().split())))
print(A)
current = 0
memo = {
    0: 0
}
for i in range(1, K + 1):
    current = A[current]
    if current in memo:
        # loop length
        length = i - memo[current]
        tmp = (K - memo[current]) % length
        # print(current, tmp)
        for j in range(tmp):
            current = A[current]
        break
    else:
        memo[current] = i
print(current + 1)

Submission status: Wrong Answer

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

X = [0, 1]

town = [-1] * (N + 1)
town[1] = 1
for i in range(1, N + 1):
    next_town = A[X[i]]
    if town[next_town] == -1:
        X.append(next_town)
        town[next_town] = i + 1
    else:
        start_i = town[next_town]
        end_i = i
        loop = X[start_i:end_i + 1]
        loop_index = (K - end_i) % len(loop)
        print(loop[loop_index])
        break

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
cc = list(map(int,input().split()))
memo = []
aa = ['.']*N
a = 1
while aa[a-1] == '.':
  memo.append(a)
  aa[a-1] = 'v'
  a = cc[a-1]
if len(memo)>K:
  print(aa[K])
else:
  b = memo.index(a)
  m = len(memo)-b
  mm = (K-b) % m
  del memo[:b]
  print(memo[mm])

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
cc = list(map(int,input().split()))
aa = [1]
flag = True
a = 1
while flag:
  aa.append(cc[a-1])
  a = cc[a-1]
  if aa.count(a) == 2:
    flag = False

b = aa.index(a)
m = len(aa)-b-1
mm = (K-b) % m
del aa[:b]
del aa[-1]
print(aa[mm])

Submission status: Wrong Answer

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

ls = [-1] * n
now = 0
cnt = 0
path = []
while 1:
    if ls[now] != -1:
        b = ls[now]
        break
    ls[now] = cnt
    path.append(now)
    now = a[now]
    cnt += 1
loop = path[b:]
if k <= b:
    print(path[k])
else:
    print(loop[(k - b) % len(loop)] + 1)

Submission status: Wrong Answer

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

ls = [-1] * n
now = 0
cnt = 0
path = []
while 1:
    if ls[now] != -1:
        b = ls[now]
        break
    ls[now] = cnt
    path.append(now)
    now = a[now]
    cnt += 1
loop = path[b:]
if k < b:
    print(path[k])
else:
    print(loop[(k - b) % len(loop)] + 1)

Submission status: Wrong Answer

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

ls = [-1] * n
now = 0
cnt = 0
path = []
while 1:
    if ls[now] != -1:
        b = ls[now]
        break
    ls[now] = cnt
    path.append(now)
    now = a[now]
    cnt += 1
loop = path[b:]
print(loop[(k - b) % len(loop)] + 1)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
A = list(map(int, input().split()))
now = 1
f = 0
past = []
for i in range(n):
	past.append(now)
	now = A[now-1]
	if now in past:
		f = 1
		break

if f==0:
	print(now)
	exit()
loop_end = len(past)
loop_start = past.index(now)
#print(past, now, loop_end, loop_start)
res = (k-loop_start)%(loop_end-loop_start)
now = past[loop_start]
for i in range(res):
	now = A[now-1]
print(now)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
A = list(map(int, input().split()))
now = 1
f = 0
past = []
for i in range(n):
	past.append(now)
	now = A[now-1]
	if now in past:
		f = 1
		break

if f==0:
	print(now)
	exit()
loop_end = len(past)
loop_start = past.index(now)
#print(past, now, loop_end, loop_start)
res = k%(loop_end-loop_start)
now = 1
for i in range(res):
	now = A[now-1]
print(now)

Submission status: Wrong Answer

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

n, k, *a = map(int, read().split())

l = [0] * (n + 1)

q = deque([])
i = a[0]

flg = True
while flg == True:
    q.append(i)
    l[i] += 1
    if l[i] == 2:
        left = q.index(i)
        right = len(q)-2
        flg = False
    i = a[i - 1]

# ループの長さ
length = right - left + 1

if k >= left:
    b = k - left
    k = b % length
    # ループのk番目が答え
    print(q[left+k-1])
else:
    print(q[k-1])

Submission status: Wrong Answer

Solution code:
a = list(map(int,input().split()))
b = [0]
b.extend(list(map(int,input().split())))
loop = []
loop.append(0)
def func():
        d = 0
        for i in range(a[0]):
            if b[d] in loop:
                return loop.index(b[d])
            else:
                loop.append(b[d])
                d = b[d]
        return 0
c = func()
if a[1] < len(loop) - 1:
    ans = loop(a[1])
    print(str(ans))
else:
    ans = ((a[1] - (c + 1)) % (len(loop) - c)) + c
    ans = loop[ans]
    print(str(ans))

Submission status: Wrong Answer

Solution code:
import numpy as np
#import math
#from decimal import *
#from numba import njit

#@njit
def main():
    (N, K) = map(int, input().split())
    A = np.array([0] + list(map(int, input().split())))

    B = [1]
    s = [True]*(N+1)
    s[1] = False
    nextTown = A[1]
    while s[nextTown]:
        B += nextTown,
        s[nextTown] = False
        nextTown = A[nextTown]
        
    B = np.array(B)
    loopIndex = np.where(B == nextTown)[0][0]
    loopLen = len(B) - loopIndex

    print(B[(K-loopIndex)%loopLen + loopIndex])

main()

Submission status: Wrong Answer

Solution code:
import numpy as np
#import math
#from decimal import *
#from numba import njit

#@njit
def main():
    (N, K) = map(int, input().split())
    A = np.array([0] + list(map(int, input().split())))

    B = [1]
    nextTown = A[1]
    while not nextTown in B:
        B += nextTown,
        nextTown = A[nextTown]
    B = np.array(B)
    loopIndex = np.where(B == nextTown)[0][0]
    loopLen = len(B) - loopIndex

    print(B[(K-loopIndex)%loopLen + loopIndex])

main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
visited = [-1 for _ in range(N)]
visited[0] = 0
k = 0
k = A[k] - 1
count = 1
while visited[k] == -1:
  visited[k] = count
  k = A[k]-1
  count += 1

roop = count - visited[k]
beforeroop = visited[k]

K = K - beforeroop
K = K % roop

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

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
visited = [-1 for _ in range(N)]
k = 0
count = 0
while visited[k] == -1:
  visited[k] = count
  k = A[k]-1
  count += 1

roop = count - visited[k]
beforeroop = visited[k]

K = K - beforeroop
K = K % roop

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

Submission status: Wrong Answer

Solution code:
n,k=list(map(int,input().split()))
m=list(map(int,input().split()))
a=[]
p=1
vis=[0]*n
while vis[p-1]==0:
    a.append(p)
    vis[p-1]=1
    p=m[p-1]

l=a.index(p)
print(k,l,a)
if k<len(a):
    print(a[k])
else:
    k-=l
    print(a[l+k%(len(a)-l)])

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline


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

    route = [0]
    visited = set([0])
    now_town = 0
    while True:
        next_town = A[now_town]
        if next_town in visited:
            break
        else:
            visited.add(next_town)
            route.append(next_town)
            now_town = next_town

    loop_start = route.index(next_town)
    loop_len = len(route[loop_start:])
    count_before_loop = len(route) - loop_len
    if K <= count_before_loop:
        ans = route[K] + 1
    else:
        r = K % loop_len
        ans = route[loop_start + r] + 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline


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

    route = [0]
    visited = set([0])
    now_town = 0
    while True:
        next_town = A[now_town]
        if next_town in visited:
            break
        else:
            visited.add(next_town)
            route.append(next_town)
            now_town = next_town

    loop_start = route.index(next_town)
    loop_len = len(route[loop_start:])
    K -= len(route) - loop_len
    r = K % loop_len
    ans = route[loop_start + r] + 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

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


def check(x):
    return A[x - 1]


x = 1
lis = deque([])

keep = [0] * (n + 1)
for i in range(n + 2):
    if keep[check(x)] != 0:
        break
    else:
        lis.appendleft(check(x))
        keep[check(x)] = 1
        x = check(x)

num = lis.index(check(x)) + 1
k = (k - (i - num)) % num
print(lis[- k - (i - num)])

Submission status: Wrong Answer

Solution code:
from collections import deque

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


def check(x):
    return A[x - 1]


x = 1
lis = deque([])
for i in range(n + 2):
    if check(x) in lis:
        break
    else:
        lis.appendleft(check(x))
        x = check(x)

num = lis.index(check(x)) + 1
k = (k - (i - num)) % num
print(lis[- k - (i - num)])

Submission status: Wrong Answer

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

move = 1
l = [1]
flag = [False]*(N+1)
flag[1] = True

for i in range(N):
    move = A[move-1]
    if flag[move]:
        break
    flag[move] = True
    l.append(move)

ind = l.index(move)
rest = (K-ind) % (len(l) - ind) + ind

print(l[rest])

Submission status: Wrong Answer

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

l = []
move = 1
l.append(move)
ind = 0
flag = [False]*(N+1)
flag[1] = True
for i in range(N):
    move = A[move-1]
    if flag[move]:
        # ind = l.index(move)
        # l = l[ind:]
        break
    flag[move] = True
    l.append(move)

# print("ind:{}".format(ind))
# print("l:{}".format(l))
ind = l.index(move)
# l = l[ind:]
rest = (K-ind) % (len(l) - ind) + ind

# print(rest)
print(l[rest])

Submission status: Wrong Answer

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

l = []
move = 1
l.append(move)
ind = 0
flag = [False]*(N+1)
flag[1] = True
for i in range(N):
    move = A[move-1]
    if flag[move]:
        ind = l.index(move)
        l = l[ind:]
        break
    flag[move] = True
    l.append(move)

rest = (K-ind) % len(l)
print(l[rest])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

N,K = list(map(int, input().rstrip().split()))
A_list = list(map(int, input().rstrip().split()))
#-----

visited_list = [1]
visited_set = set([1])
idx = 0

while True:
    next_idx = A_list[idx] - 1
    
    if (next_idx+1) in visited_set:
        break
    else:
        visited_list.append(next_idx+1)
        visited_set.add(next_idx+1)
        idx = next_idx


cycle_start = visited_list.index(next_idx+1)  # 0-index
cycle_length = len(visited_list) - cycle_start

remain = (K - cycle_start) % cycle_length  # 0-index
idx = cycle_start + remain

print(visited_list[idx])

Submission status: Wrong Answer

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

now=an[0]
bn[1]=0
for i in range(1, k+1):
    now = an[now-1]
    if bn[now] >0:
        rp =i-bn[now]
        p= k%rp
        for j in range(p+1):
            now = an[now-1]
        print(now)
        exit(0)
    bn[now]=i
print(now)

Submission status: Wrong Answer

Solution code:
n, k  = map(int, input().split())
an = list(map(int, input().split()))
p = k%n

now=an[0]
for _ in range(p-1):
    now = an[now-1]
print(now)

Submission status: Wrong Answer

Solution code:
#D
from collections import deque
n,k = map(int,input().split())
a = list(map(int,input().split()))
tel = deque()
tel.append(1)
visit = [False for _ in range(n)]
visit[0] = True
for i in range(n):
    nx = a[tel[i]-1]
    if visit[nx-1] == True :
        tel.append(nx)
        #ループの始まりのindexをidxに格納
        idx = tel.index(nx)
        break
    tel.append(nx)
    visit[nx-1] = True
    
#print(tel)
if k - idx <=0:
    print(tel[k-1])
else:
    k -= idx
    loop_num = len(tel) - idx - 1
    #print('idx:',idx)
    #print('loop_num:',loop_num)
    goal = tel[idx + k%loop_num]
    
    print(goal)

Submission status: Wrong Answer

Solution code:
#D
from collections import deque
n,k = map(int,input().split())
a = list(map(int,input().split()))
tel = deque()
tel.append(1)
visit = [False for _ in range(n)]
visit[0] = True
for i in range(n):
    nx = a[tel[i]-1]
    if visit[nx-1] == True :
        tel.append(nx)
        #ループの始まりのindexをidxに格納
        idx = tel.index(nx)
        break
    tel.append(nx)
    visit[nx-1] = True
    
#print(tel)
#print(visit)
k -= idx
loop_num = len(tel) - idx - 1
#print('idx:',idx)
#print('loop_num:',loop_num)
goal = tel[idx + k%loop_num]
    
print(goal)

Submission status: Wrong Answer

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

tel = deque()
tel.append(1)
for i in range(n):
    nx = a[tel[i]-1]
    if nx in set(tel):
        tel.append(nx)
        #ループの始まりのindexをidxに格納
        idx = tel.index(nx)
        break
    tel.append(nx)
    
#print(tel)
if k - idx <=0:
    print(tel[k-1])
else:
    k -= idx
    loop_num = len(tel) - idx - 1
    #print('idx:',idx)
    #print('loop_num:',loop_num)
    goal = tel[idx + k%loop_num]
    
    print(goal)

Submission status: Wrong Answer

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

tel = deque()
tel.append(1)
for i in range(n):
    nx = a[tel[i]-1]
    if nx in tel:
        tel.append(nx)
        #ループの始まりのindexをidxに格納
        idx = tel.index(nx)
        break
    tel.append(nx)
    
#print(tel)
if k - idx <=0:
    print(tel[k-1])
else:
    k -= idx
    loop_num = len(tel) - idx - 1
    #print('idx:',idx)
    #print('loop_num:',loop_num)
    goal = tel[idx + k%loop_num]
    
    print(goal)

Submission status: Wrong Answer

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

tel = [1]
for i in range(n):
    nx = a[tel[i]-1]
    if nx in set(tel):
        #ループの始まりのindexをidxに格納
        idx = tel.index(nx)
        tel.append(nx)
        break
    else:
        tel.append(nx)

if k - idx <=0:
    print(tel[k-1])
else:
    k -= idx
    loop_num = len(tel) - idx - 1
    goal = tel[idx + k%loop_num]
    #print('idx:',idx)
    #print('loop_num:',loop_num)
    print(goal)

Submission status: Wrong Answer

Solution code:
#####################################################################################################
##### 深さ優先探索 幅優先探索　（グラフ）
#####################################################################################################

'''

キューに頂点を入れる回数は各々高々１回のみ。
各辺を使う回数は高々一回のみ（辺を戻るような探索は枝切りされている）
結果として、計算量はO(N + M)

'''

import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
from copy import deepcopy



class Graph:
    def __init__(self, n, dictated=False, decrement=True, edge=[]):
        self.n = n
        self.dictated = dictated
        self.decrement = decrement
        self.edge = [set() for _ in range(self.n)]
        self.parent = [-1]*self.n
        self.info = [-1]*self.n
        for x, y in edge:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edge[x].add(y)
        if self.dictated == False:
            self.edge[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edge[i] = set(map(lambda x:x-1, adjacent_list))
        else:
            self.edge[i] = set(adjacent_list)

    def cycle_detector(self, start, time=0, save=False):
        """
        :param p: スタート地点
        :param save: True = 前回の探索結果を保持する
        :return: 各点までの距離と何番目に発見したかを返す
        """

        edge2 = deepcopy(self.edge)

        if self.decrement:
            start -= 1
        if not save:
            self.parent = [-1] * self.n

        p, t = start, time
        self.parent[p] = -2
        cycle_end = False
        cycle_time = 0
        cycle = []
        while True:
            if edge2[p]:
                q = edge2[p].pop()
                if q == self.parent[p] and not self.dictated:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if self.parent[q] != -1:
                    """ サイクルで同一点を訪れた時の処理 """
                    if not cycle:
                        cycle.append(q + self.decrement)
                        cycle.append(p + self.decrement)
                        cycle_time = t
                    """"""""""""""""""""
                    continue
                self.parent[q] = p
                p, t = q, t + 1
            else:
                """ 探索完了時の処理 """
                """"""""""""""""""""
                if p == start and t == time:
                    break
                p, t = self.parent[p], t-1
                """ 二度目に訪問時の処理 """
                if cycle and t == cycle_time - 1 and not cycle_end:
                    if cycle[0] == p + self.decrement:
                        cycle_end = True
                        continue
                    cycle.append(p + self.decrement)
                    cycle_time = t

                """"""""""""""""""""
        cycle = list(reversed(cycle))
        return [cycle[-1]] + cycle[:-1]

    def tree_counter(self, detail=False):
        """
        :param detail: True = サイクルのリストを返す
        :return: 木（閉路を含まない）の個数を返す
        """
        self.parent = [-1] * self.n

        connection_number = 0
        cycle_list = []

        for p in range(self.n):
            if self.parent[p] == -1:
                connection_number += 1
                cycle = self.cycle_detector(p + self.decrement, save=True)
                if cycle:
                    cycle_list.append(cycle)
        if not detail:
            return connection_number - len(cycle_list)
        else:
            return cycle_list

    def draw(self):
        """
        :return: グラフを可視化
        """
        import matplotlib.pyplot as plt
        import networkx as nx

        if self.dictated:
            G = nx.DiGraph()
        else:
            G = nx.Graph()
        for x in range(self.n):
            for y in self.edge[x]:
                G.add_edge(x + self.decrement, y + self.decrement)

        nx.draw_networkx(G)
        plt.show()

##################################################################


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

M = N
graph = Graph(N,dictated=True)
for i in range(1,M+1):
    x = i
    y = A[i-1]
    graph.add_edge(x, y)

p = 0
cnt = 0
if K <= N:
    while cnt + 1 <= K:
        p = A[p] - 1
        cnt += 1
    res = p + 1
else:
    cycle = list(graph.cycle_detector(1))
    len_cycle = len(cycle)
    p = 0
    cnt = 0
    res = 0
    while p != cycle[0] - 1:
        p = A[p] - 1
        cnt += 1
    k = (K - cnt) % len_cycle
    res = cycle[k]
print(res)

Submission status: Wrong Answer

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

l = []
move = 1
l.append(move)
ind = 0
flag = [False]*(N+1)
for i in range(N):
    move = A[move-1]
    if flag[move]:
        ind = l.index(move)
        l = l[ind:]
        break
    flag[move] = True
    l.append(move)

rest = (K-ind) % len(l)
print(l[rest])

Submission status: Wrong Answer

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