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:
# from math import factorial,sqrt,ceil,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
# import networkx as nx
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb

# slist = "abcdefghijklmnopqrstuvwxyz"
N,K = map(int,input().split())
lisA = [0] + list(map(int,input().split()))
# arrA = np.array(input().split(),dtype=np.int64)

checked = [1]
i = 1
for _ in range(N+1):
    if not lisA[i] in checked:
        checked.append(lisA[i])
        i = lisA[i]
    else:
        checked.append(lisA[i])
        break

# print(checked)
idx = checked.index(checked[-1])
rooplis = checked[idx:-1]
warukazu = len(rooplis)
ans = rooplis[(K-idx) % warukazu]
print(ans)
# print(*ans)   # unpackして出力。間にスペースが入る
# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

A = list(map(int, input().split()))
d = {}

d[1] = A[0]

idx = 1
start = 0
count = 0
while True:
  count += 1
  d[idx] = A[idx-1]
  idx = A[idx-1]
  if idx in d:
    start = idx
    break


e = {}
l = []
while True:
  e[start] = A[start-1]
  l.append(e[start])
  start = A[start-1]
  if start in e:
    break


amari = ((K-count-len(l)) % len(l))
print(l[amari-1])

Submission status: Wrong Answer

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

                b.pop(-1)
                I = c[k]
                break
    if check==-1:
        e=K%len(b)
        print(b[e-1])
    else:
        d=len(b)-I
        e=(K-I+1+check)%d
        print(b[e-1])

Submission status: Wrong Answer

Solution code:
import sys 
n,m=list(map(int,input().split(" ")))

arr=list(map(int,input().split(" ")))

def bfs(start,n,visited,m):
	# count=0

	# l2=[i+1]
	
	# count+=1
	moves=[]
	moves.append(start)
	visited[start]=1
	left=-1
	fl=0
	while(True):

		j=arr[start]-1
		
		if(visited[j]==0):
			moves.append(j)
			visited[j]=1
			# l2.append(j)
			# q.append(j)

			# count+=1
		else:
			left=j
			fl=1
			break
		start=j


	# print(moves,left)
		# q.popleft()
	# print(left,moves)
	if(left!=-1):
		pre=[]
		post=[]
		for i in range(len(moves)):
			if(moves[i]==left):
				pre=moves[:i]
				post=moves[i:]
				break
		if(m<=len(pre)):
			print(pre[m-1]+1)
		else:
			m-=len(pre)
			# print

			print(post[m%len(post)]+1)


	else:
		# curr=0

		print(pre[m%len(pre)]+1)
visited=[0]*n
bfs(0,n,visited,m)

Submission status: Wrong Answer

Solution code:
# D

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

def compute(city, K):
    for i in range(K):
        # print('\t', city)
        city = As[city-1]
    print(city)

cities_visited = [False] * N
i = 0
city = 1
city_visited_time = {}

while not cities_visited[city - 1]:
    # print(city)
    cities_visited[city - 1] = True
    city_visited_time[city-1] = i
    city = As[city-1]
    i += 1

loop_start = city_visited_time[city-1]
loop_end = i

if loop_end - loop_start == 1 and loop_start <= K:
    print(city)

div = (K - loop_start) // (loop_end - loop_start)
compute(city, K - loop_start - div * (loop_end - loop_start))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = 1
c = [0] * n
c[0] = 1
while c[b-1]<3 and k > 0:
	b = a[b-1]
	c[b-1] += 1
	k -= 1
n = k % n
for i in range(n):
	b = a[b-1]
print(b)

Submission status: Wrong Answer

Solution code:
import sys
n, k = map(int, input().split())
l = list(map(int, input().split()))
count = 0
li = [0 for _ in range(n)]
b = 1
for i in range(1,n + 1):
#     print(b)
    if li[b-1] != 0:
        break
    li[b-1] = i
    b = l[b-1]
    count += 1
#     print('count',count)


d = count - li[b-1] + 1
intercep = li[b-1] -1
# print('d', d, 'intercep', intercep)
if k <= intercep:
    for i in range(k):
        b = l[b-1]
        print(b)
        sys.exit()
    
mod = (k - intercep) % d
b = 1
for i in range(intercep + mod):
#     print('b',b)
    b = l[b-1]
print(b)

Submission status: Wrong Answer

Solution code:
import sys
from math import factorial
from collections import Counter
from fractions import Fraction
import heapq, bisect, fractions
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
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()))
MOD = 10**9 + 7

n, k = MAP()
a = LIST()
tugi = [0]+a
towns = [i for i in range(1, n+1)]
routes =[]
cyclestart = []
town  =1
temp = [town, ]
towns.remove(town)
while True:
    town = tugi[town]
    if town not in towns:
        i = temp.index(town)
        notcycle = temp[:i]
        cycle = temp[i:]
        cyclestart.append(town)
        break
    towns.remove(town)
    temp.append(town)
k -= len(notcycle)
print(cycle[k%len(cycle)])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
cnt = 1
next = a[0]
tmp_list = [a[0]]
roop_list = []
tmp_set = set([a[0]])
while(True):
    next = a[next-1]
    if next in tmp_set:
        hajimari = tmp_list.index(next)
        roop_list = tmp_list[hajimari:]
        cnt -= hajimari
        break
    tmp_set.add(next)
    tmp_list.append(next)
    cnt +=1
print(roop_list[((k-hajimari)%cnt)-1])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = {}
tmp = list(map(int, input().split()))
for i, num in enumerate(tmp):
  a[i+1] = num

Submission status: Wrong Answer

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

l = [0]*n
s = set()
x = 0

for i in range(n):
    machi = a[x]
    if machi in s:
        hajime = l.index(machi)
        owari = i-1
        repeat = l[hajime:owari+1]
        break
    x = machi-1
    l[i] = machi
    s.add(machi)
else:
    amari = k%n
    print(l[amari-1])
    exit()

if k < owari:
    print(l[k-1])
else:
    amari = (k-hajime)%len(repeat)
    if hajime + amari == 0:
        print(repeat[-1])
    else:
        print(l[hajime+amari-1])

Submission status: Wrong Answer

Solution code:
def calc(i):
    ans_list = [i]
    ans_set = set([i])
    count = 1
    i = a[i]
    while (i not in ans_set) & (count <= n):
        ans_list.append(i)
        ans_set.add(i)
        count += 1
        i = a[i]
    index = ans_list.index(i)
    ans_list.append(i)
    return count, ans_list

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

count, ans_list = calc(0)
if count <= n:
    index = ans_list.index(ans_list[-1])
    k = k - index
    ans_list = ans_list[index + 1:]
    print(ans_list[k % len(ans_list) - 1] + 1)
else:
    k = k % n
    print(ans_list[k] + 1)

Submission status: Wrong Answer

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

b = A[0]
count = 1

X = []
flag = 0
loop = 0
ans = 0

if A[0] == 1:
    ans = 1

elif N>=K:
    for i in range(K-1):
        c = A[b-1]
        b = c
    ans = b
else:   
    #print("a")
    for i in range(N):
        c = A[b-1]
        b = c
        l = len(X)
        for j in range(l):
            if b == X[j-1]:
                loop = i - j + 1
                flag = 1
                Z = i + 1
                #print(loop)
                break


        if flag == 1:
            break
        else:
            X.append(b)
            #print(X)
            
    #print(loop)        
    Y = K%loop
    #print(Y)
    #print(Z)
    #print(Z+Y-1-loop)
    ans = A[Z+Y-1-loop]

print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
A=[i-1 for i in A]
c=A[A[0]]
 
s=set()
s.add(0)
s.add(A[0])
I=[]#訪れた島を記憶
I.append(0)
I.append(A[0])

while True:
  if c in s:
    break
  s.add(c)
  I.append(c)
  c=A[c]

a=I.index(c)
K-=a

ans=A[0]
for i in range(a-1):
  ans=A[ans]
#ansが今いる島
mod=len(s)-a
K%=mod

if K==0:
  print(ans+1)
  exit()
#ans=A[0]
#for i in range(a):
#  ans=A[ans]

for i in range(K-1):
  ans=A[ans]
print(ans+1)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

""" Input
S = input().rstrip()
N = int(input())
A = np.array(input().split(), dtype=np.float64)
D = [int(input()) for _ in range(N)]
AB = [[int(x) for x in input().split()] for _ in range(N)]
PX = [[int(x) for x in input().split()] for _ in range(Q)]
"""

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

ayumi = [A[0]]
loop = []

counter = 0
flag = True
while True:
    next = ayumi[-1]
    tmp = A[next - 1]

    if flag == False or tmp in ayumi:
        if flag:
            koremade = len(ayumi)
            start_number = tmp
            counter += 1
            flag = False
            loop.append(tmp)
        else:
            if start_number == tmp:
                break
            counter += 1
            loop.append(tmp)

    ayumi.append(tmp)

a = K
a -= koremade
amari = a % counter

print(loop[amari - 1])

Submission status: Wrong Answer

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

city = [-1 for i in range(0,N,1)]#0~N-1
count = 0
nex_city = 0
city[0]=0
while True:
    city[nex_city] = count
    nex_city = A[nex_city]-1
    count+=1
    if city[nex_city] >= 0:
        break

X = nex_city
Y = count - city[nex_city]

nex_city = 0
if K < X:
    for i in range(0,K,1):
        nex_city = A[nex_city]-1
    print(nex_city+1)
    exit()

nex_city = 0
for i in range(0,X+(K-X)%Y,1):
    nex_city = A[nex_city]-1
print(nex_city+1)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
n,k = map(int,input().split())
a = list(map(int,input().split()))
ans = []
key = -1
p = 0
while True:
    ans.append(p)
    p = a[p]-1
    if p in ans:
        key = ans.index(p)
        break
if len(ans) == 1:
    print(1)
else:
    r = ans[key:]
    mod = (k-key)%len(r)
    if mod == 0:
        print(r[0]+1)
    else:
        print(r[mod]+1)

Submission status: Wrong Answer

Solution code:
def main():
    [n, k] = [int(i) for i in input().split(" ", 2)]
    t = [int(i) for i in input().split(" ")]
    t.insert(0, 1)
    h = [1]
    c = 1
    while True:
        c = t[c]
        h.append(c)
        if c in h[:-1]:
            h = h[:-1]
            break
    # print(h)
    s = (k + 1) % len(h)
    if s == 0:
        print(h[-1])
    else:
        print(s)


main()

Submission status: Wrong Answer

Solution code:
import sys
n,k=map(int,input().split())
a=list(map(int,input().split()))
visited=[0]*n
town=0
Town=0
visited[0]=0
lst=[]
if a[0]==1:
  print(1)
  sys.exit()
for i in range(n):
  town=a[town]-1
  if visited[town]!=0 or town==0:
    lst.append([town,visited[town],i+1])
    break
  else:
    visited[town]=i+1
Lst=[]
print(lst)
town=lst[0][0]
Lst.append(town)
if lst[0][2]-lst[0][1]-1==0:
  if k<lst[0][1]:
    print(visited.index(k)+1)
    sys.exit()
  else:
    print(lst[0][0]+1)
    sys.exit()
for i in range(lst[0][2]-lst[0][1]-1):
  town=a[town]-1
  Lst.append(town)
if k<=lst[0][1]:
  print(visited.index(k)+1)
else:
  k=k-lst[0][1]
  l=len(Lst)
  k=k%l
  print(Lst[k]+1)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
b=[0]*n
c=[0]*n
total=0
b[0]+=1
next=a[0]
while True:
  total+=1
  if b[next-1]==0:
    b[next-1]+=1
    c[next-1]+=total
    next=a[next-1]
  else:
    total1=total
    k-=(c[next-1])
    total-=c[next-1]
    start=next-1
    break
if total1<=k:
  start=0
  for i in range(k):
    start=a[start]-1
  print(start+1)
else:
  k%=total
  for i in range(k):
    start=a[start]-1
  print(start+1)

Submission status: Wrong Answer

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) % len(arr)
    # print(arr, r)
    print(arr[r] + 1)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
C=[0]+[-1]*(n-1)
p=1
c=0
s=-1
e=-1
for i in range(n):
    p=A[p-1]
    c+=1
    if C[p-1]==-1:
        C[p-1]=c
    else:
        s=C[p-1]
        e=c
        break
P=1
if s!=-1 and e!=-1:
    if k<=s:
        while k>1:
            P=A[P-1]
            k-=1
        print(P)
    else:
        l=(k-s)%(e-s)
        k=s+l+1
        while k>1:
            P=A[P-1]
            k-=1
        print(P)
else:
    if k<=n:
        while k>1:
            P=A[P-1]
            k-=1
        print(P)
    else:
        while n>1:
            P=A[P-1]
            n-=1
        print(P)

Submission status: Wrong Answer

Solution code:
def main():
    N, K = map(int, input().split())
    A = [int(a) for a in input().split()]

    visited = [False for i in range(N)]

    ind = 0
    for i in range(N):
        if visited[ind] == False:
            visited[ind] = True
            ind = A[ind] - 1
        else:
            break

    start = ind
    ind = start
    cnt = 0
    for i in range(N):
        if A[ind] - 1 == start:
            cnt += 1
            break
        else:
            ind = A[ind] - 1
            cnt += 1

    step = 0

    if K >= cnt:
        step = K%cnt
    else:
        step = K

    ind = 0
    for i in range(step):
        ind = A[ind] - 1

    print(ind + 1)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k= map(int,input().split())
temp = list(map(int,input().split()))
As = [0]*(n+1)
for i in range(n):
    As[i+1] = temp[i]

visit_list = {}
now = 1
visit_list[1] = 0
visit_num = 1

while True:
    now = As[now]
    if now in visit_list:
        break
    visit_list[now] = visit_num
    visit_num += 1

loop_num = visit_num - visit_list[now]

res = k%loop_num
res -= visit_list[now]%loop_num

for i in range(res):
    now = As[now]

print(now)

Submission status: Wrong Answer

Solution code:
from collections import Counter

(town, tele)=[int(x) for x in input().split()]
pos=[int(x) for x in input().split()]
move=[pos[0]]
move_dict={i:0 for i in range(1, town+1)}
while move_dict[move[-1]] <= 1:
  move.append(pos[move[-1]-1])
  move_dict[move[-1]]+=1
loop_move=move[move.index(move[-1]):-1]
print(loop_move[(tele-(len(move)-1))%len(loop_move)-1])

Submission status: Wrong Answer

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

towns = [0] * N

town = 1
i = 0
while True:
    if towns[town-1] < 2:
        
        if towns[town-1] == 0:
            i += 1
            
        towns[town-1] += 1
        town = A[town-1]
    else:
        s = town
        break
    
loop = towns.count(2)
i = i - loop
k = (K - i) % loop

if K < i:
    town = 1
    for _ in range(k):
        town = A[town-1]
    print(town)

if k == 0:
    print(s)
    exit()

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

Submission status: Wrong Answer

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

index = 0
count = 0
node = [1]
while True:
    next = A[index]
    node.append(next)
    if A[next - 1] in node:
        catch_point = A[next - 1]
        break
    index = next - 1

for point in node:
    if point == catch_point:
        break
    else:
        count += 1

idx =  (K - count) % (len(node) - count)

print(node[count + idx])

Submission status: Wrong Answer

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

visited = [-1] * N
visited[0] = 0
nxt = 1
cnt = 1
for i in range(N):
    nxt = A[nxt-1]
    if visited[nxt-1] == -1:
        visited[nxt-1] = i+1
    else:
        cycl = i + 1 - visited[nxt-1]
        m = visited[nxt-1]
        break
    cycl = N
    m = 0

k = (K - m) % cycl + m

for i in range(N):
    if visited[i] == k:
        print(i+1)
        break

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
i = 0
ans = 0
root = [-1] * n
flag = [False] * n
j = 0
while flag[a[i] - 1] == False:
    flag[a[i] - 1] = True
    root[j] = a[i]
    i = a[i] - 1
    j += 1
s_i = root.index(a[i])
i = 0
for i in range(k % (j - s_i)):
    ans = root[i]
    i = root[i] - 1

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
# import math
# import copy
# from collections import deque
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10000)
# from numba import njit


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

    route = np.array([1])

    pre = 1
    while True:
        now = A[pre-1]
        if now in route:
            break
        route = np.append(route,now)
        pre = now

    start = int(np.where(route == now)[0])

    if start+1 != N:
        K -= start
        loop = route[start:]
        # print(loop,K)
        M = len(loop)
        K %= M
        res = loop[K]
    else:
        res = route[K-1]

    print(res)



main()

Submission status: Wrong Answer

Solution code:
from collections import deque

n, k = map(int, input().split())
a_list = list(map(int, input().split()))
route = []
roop = []

pos = 1
while k > 0:
    pos = a_list[pos-1]
    if pos in route:
        if pos in roop:
            k -= k % (k * (k // len(roop)))

        roop.append(pos)
    else:
        roop = []

    route.append(pos)
    k -= 1

print(pos)

Submission status: Wrong Answer

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

for i in range(100000) :
    l = a[l]-1 
    count = +1
    if l == 0 :
        x = k%count
        for i in range(x) :
            l = a[l]-1
            
        print(l+1)
        exit()
        
print(l+1)

Submission status: Wrong Answer

Solution code:
N,K = map(int, input().split())
A =[0]
B=list(map(int, input().split()))
for m in range(N):
    A.append(B[m])
place=[]
i=1
count=0
while i not in place:
    place.append(i)
    i=A[i]
    count+=1
print(place)
print(i)
loop=[i]
start=i
j=A[i]
count+=1
while j!=start:
    loop.append(j)
    j=A[j]
    count+=1
print(loop)
num=(K-count)%len(loop)
print(loop[num])

Submission status: Wrong Answer

Solution code:
def resolve():
  N, K = map(int, input().split(" "))
  A = [int(x) - 1 for x in input().split(" ")]

  history = []
  current = 0
  while True:
    history.append(current)
    current = A[current]
    if current in history:
      loop_length = len(history[history.index(current):] )
      if loop_length == 1:
        return print(current + 1)
        return True

      length_to_loop = len(history[:history.index(current)])
      additional_way = (K-length_to_loop)%loop_length
      print(A[length_to_loop + additional_way] + 1)
      return True

if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

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

fi = a[0]-1
s = 0
for i in range(n):
    t = a[fi]
    s+=1
    fi = t-1
    if t==a[0]:
        break
amari = k%s
fi = a[0]-1
if amari==0:
    amari=s
for _ in range(amari-1):
    t = a[fi]
    fi = t-1
print(t)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
town = 1
record = [1]
for i in range(K):
    town = A[town-1]
    if town in record:
        break
    record.append(town)
    
roop = len(record)
amari = K%roop


    
print(record[amari])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

warpmap = {}

for town_num, to_warp in enumerate(A):
    
    town_num = town_num + 1
    warpmap[f"{town_num}"] = f"{to_warp}"

def check_loop(start='1', counter=0):
    past_towns = deque()

    for _ in range(N):
        counter += 1

        nextmap = warpmap[start]

        if nextmap in past_towns:
            return counter, counter - past_towns.index(nextmap)
        else:
            past_towns.append(start)

        start = nextmap

def getterminal(n, start):
    if n == 0:
        return start
    else:
        for _ in range(1, n + 1):
            nextmap = warpmap[start]
            start = nextmap

        return nextmap

pasttime, looptime = check_loop()

print(getterminal(n=(K - pasttime) % looptime, start=getterminal(n=pasttime, start='1')))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
if k <= n:
    pos = a[0] - 1
    for i in range(k):
        ans = a[pos]
        pos = a[ans] - 1
    print(a[ans])
else:
    nums = {0: 1}
    cnt_one = 0
    cnt_two = 0
    pos = a[0] - 1
    num_list = [0]
    while(True):
        if pos not in nums:
            nums[pos] = 1
            num_list.append(pos)
        else:
            nums[pos] += 1
            if nums[pos] == 3:
                nums[pos] -= 1
                break
        pos = a[pos] - 1
    for key, value in nums.items():
        if value == 1:
            cnt_one += 1
            num_list.remove(key)
        else:
            cnt_two += 1
    pos_ans = (k - cnt_one) % cnt_two
    ans = num_list[pos_ans] + 1
    print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
A = [val - 1 for val in A]
# print(A)
route = [0]
seen = {0}
here = 0
for _ in range(K):
    here = A[here]

    if here in seen:
        start = route.index(here)
        period = len(route) - start
        # print(period)
        r = (K - start + 1) % period
        if r == 0:
            idx = period + start - 1
        else:
            idx = r + start - 1
        print(route[idx] + 1)
        break
    seen.add(here)
    route.append(here)
else:
    print(route[-1])
    # print(route)
# print(period)
# else:
#     print(route[K] + 1)

Submission status: Wrong Answer

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

num = K
memo = []
town = 1
for _ in range(N):
    memo.append(town)
    if not A[town-1] in memo:
        town = A[town-1]
        num -= 1
    else:
        index = memo.index(A[town-1])
        l = len(memo) - index
        if num % l == 0:
            town = memo[-1]
        else:
            town = memo[index + (num % l) - 1]
        break
print(town)

Submission status: Wrong Answer

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

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

now=1
count=0
newWhere=[1]
while count>=0:
  now=where[now-1]
    
  count=count+1


  if now in newWhere:
    break
  newWhere.append(now)
  
k=k%count

print(newWhere[k])

Submission status: Wrong Answer

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)
#print('B',B)
if B==0:
    print(ptrn[0]+1)
else:
    print(ptrn[B]+1)
    #print('0000000')

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = [1]
x = 1

for i in range(n):
  x = a[x-1]
  if not(x in b):
    b.append(x)
  else:
    c = b.index(x)
    break
d = (k-c) % (len(b)-c)
print( b[c+d] )

Submission status: Wrong Answer

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

i=0
locate=1
flag=[0]*n
flag2=0
while(True):
    flag[locate-1]+=1
    if flag[locate-1]==1 and flag2==0:
        i=0
        flag2=1
    elif flag[locate-1]==2:
        break
    locate=a[locate-1]
    i+=1
k=k%i+i
for j in range(k):
    locate=a[locate-1]
print(locate)

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
A = list(map(int, input().split()))
where = [0 for k in range(N)]
where[0]=1
loop=0
for k in range(N):
    where[k+1] = A[where[k]-1]
  
    if where[k+1] in where[0:k]:
        end = k+1
        for j in range(len(where)):
            if where[k+1] == where[j]:
                start = j
                break
        loop = end -start
      
        break
loopbefore = K -start

loopafter = loopbefore%loop

where2 = [where[end]]
for k in range(loopafter):
    where2.append(A[where2[k]-1])
print(where2[-1])

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
A = list(map(int, input().split()))
d=k%n
print(A[A[d-1]-1])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
senni=[1]
dabu=False
while dabu == False:
    if a[senni[-1]-1] in senni:
        dabu = True
        t=len(senni)-(senni.index(a[senni[-1]-1]))
        break
    senni.append(a[senni[-1]-1])
if t<=k and k%t < senni.index(a[senni[-1]-1]):
    ad=0
    while k%t+ad < senni.index(a[senni[-1]-1]):
        ad += t
    ans = senni[k%t+ad]
else:
    ans=senni[k%t]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import copy
import math
import bisect
import pprint
import bisect
from functools import reduce
from copy import deepcopy
from collections import deque
from decimal import *

import numpy

def costCalc1(index,cost):
    if costList1[index] == -1:
        costList1[index] = cost
        costCalc1(a[index]-1,cost+1)
    else:
        costCalc2(index,0)


def costCalc2(index,cost):
    if costList2[index] == -1:
        costList2[index] = cost
        costCalc2(a[index]-1,cost+1)

if __name__ == '__main__':
    sys.setrecursionlimit(10 ** 6)
    n, k = map(int, input().split())
    a = [int(i) for i in input().split()]
    costList1 = [-1]*n
    costList2 = [-1]*n

    costCalc1(0,0)
    maxCount1 = max(costList1)+1
    maxCount2 = max(costList2)+1

    if costList1==costList2:
        k2 = k % maxCount1
        print(costList1.index(k2) + 1)
    else:
        k2 = k- maxCount1
        k2 = k2 % maxCount2
        print(costList2.index(k2) + 1)

Submission status: Wrong Answer

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

loop_lis = [0]
visited = [-1 for _ in range(N)]
visited[0] = 0
for i in range(K):
  if visited[A[loop_lis[-1]]] != -1:
    loop_time = i+1-visited[A[loop_lis[-1]]]
    start_loop = visited[A[loop_lis[-1]]]
    break
  visited[A[loop_lis[-1]]] = i+1
  loop_lis.append(A[loop_lis[-1]])

if i == K-1:
  print(loop_lis[-1]+1)
else:
  print(loop_lis[start_loop+(K-start_loop)%loop_time]+1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
i_to_a = {i+1: int(a) for i, a in enumerate(input().split())}

seen_d = {i: 0 for i in range(1, n+1)}
seen = []

next_v = 1
loop_start_index = 0
while True:    
    if seen_d[next_v]:
        break
    seen_d[next_v] = 1
    seen.append(next_v)
    next_v = i_to_a[next_v]
loop_start_index = seen.index(next_v)
to_loop = seen[:loop_start_index]
additional = seen[:loop_start_index]
loop = seen[loop_start_index:]

additional_l = len(additional)
loop_l = len(loop)

s = (k - additional_l) % loop_l

if k > additional_l:
    print(seen[additional_l + s])
else:
    print(seen[s])

Submission status: Wrong Answer

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):
  return times
  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: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys
n,k=map(int,input().split())
alist=list(map(int,input().split()))

vislist=[1]
visset={1}
loopflag=True
endflag=False
donek=0
ima=1

while loopflag:
    ima=alist[ima-1]
    if ima in visset:
        loopflag=False
        if ima == alist[ima-1]:
            endflag=True
    else:
        vislist.append(ima)
        visset.add(ima)

        donek+=1

        if donek == k:
            loopflag=False
            endflag=True

if endflag:
    print(ima)
    sys.exit()

loopstartindex=vislist.index(ima)
looplength=len(visset)-loopstartindex
print(vislist[loopstartindex+(k+1-loopstartindex)%looplength-1])