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

rs = 0
p = -1
r = ""
d = 1
# i回目
if N > K:
  for i in range(K+1):
    r += str(d)
    d = A[d - 1]
else:
  for i in range(N+1):
    r += str(d)
    d = A[d - 1]
    for j in range(len(r)):
      if r[j] == str(d):
        rs = j
        p = i - j + 1
        break
if p == -1:
  print(r[-1])
else:
  print(r[rs+(K-rs)%p])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
i = 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])
x = 0
ans = root[-1]
for i in range(k % (j - s_i)):
    ans = a[x]
    x = a[x] - 1

print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
A = [0] + A
c = {}
c[1] = 0
n = 0
k = 1
while c.get(A[k]) is None or c[A[k]] != 2:
    if c.get(A[k]) is None:
        c[A[k]] = 0
    else:
        c[A[k]] += 1
    n += 1
    k = A[k]
from collections import Counter
num = Counter(c.values())[2]
sa = len(c)-num
bbb = K - sa
m = bbb % num
abc = list(c.keys())
abc = abc[sa:len(c)]
print(abc[m])

Submission status: Wrong Answer

Solution code:
import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left
from functools import reduce
input = sys.stdin.readline 
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_list(N): return [s_list() for _ in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    n, k = i_map()
    num_list = i_list()

    trans_list = [0] * (n)

    next_trans = num_list[0]

    for i in range(n):
        trans_list[i] = next_trans
        next_trans = num_list[next_trans-1]

    tras_index = k % n

    checkflag = 1
    if trans_list.count(1) >= 1:
        checkflag = 0

    print(trans_list[tras_index-checkflag])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
li = list(map(int,input().split()))
now = li[0]
for _ in range(K):
    now = li[now - 1]
print(now)

Submission status: Wrong Answer

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

lst = []
n = 0
for i in range(N):
    n = A[n]-1
    if A[n] in lst:
        n0 = lst.index(A[n])
        n1 = i
        break
    lst.append(A[n])

num = n1 - n0
if num == 0:
    e = 0
K -= n0
r = K % num
n = n0

for _ in range(r):
    n = A[n] - 1

print(n0+n+1)

Submission status: Wrong Answer

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

# from fractions import gcd
from math import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement

N, K = [int(_) for _ in input().split()]
A = [int(_) for _ in input().split()]

index = 0
dict_root = { i:0 for i in range(N)}
rootnum = 1

for i in range(N):
    dict_root[index] = rootnum

    if dict_root[A[index]-1] != 0:
        ho = dict_root[A[index]-1] - 1
        break
    rootnum += 1
    index = A[index] - 1

nokori = (K-ho) % (rootnum-ho) + 1

for key, value in dict_root.items():
    if value == nokori+ho:
        print(key+1)
        break

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


div = (K - loop_start) // (loop_end - loop_start)
if K - loop_start - div * (loop_end - loop_start) <= 0:
    compute(1, K)
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()))

h = set([])

c = 0
for i in range(2 * n):
  c = a[c] - 1
  if n < i:
    if c + 1 in h:
      break
    else:
      h.add(c + 1)

c = 0
d = 0
for i in range(n):
  c = a[c] - 1
  if c in h:
    break
  else:
    d += 1

c = 0
if d >= k:
  print("sss")
  for i in range(k):
    c = a[c] - 1
else:
  for i in range(d + (k % len(h))):
    print("{} {}".format(c, a[c]))
    c = a[c] - 1

print(c + 1)

Submission status: Wrong Answer

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

n = a[0]
k = a[1]

src = 0
passed = [1]
turn = []
flag = 0

for i in range(k):
  dest = b[src]
  if dest in passed:
    if dest in turn:
      count = len(turn)
      now = i + 1
      rep = (k - now) % count
      ans = turn[rep]
      print(ans)
      flag = 1
      break
    else:
      turn.append(dest)
  else:
    passed.append(dest)
  src = dest - 1

if flag == 0:
  print(src)

Submission status: Wrong Answer

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

visited=[0]*N#訪問フラグ
ima_pos=0#現在地
mirai_pos=0#移動先

count_first=0#一巡目のループ
first_DP=[]
while(visited[ima_pos]==0):
  visited[ima_pos]=1#訪れたら更新
  mirai_pos=A[ima_pos]-1
  ima_pos=mirai_pos
  first_DP.append(ima_pos)#何番目のインデックスに移動するか
  count_first+=1#何回移動したか

second_start=ima_pos#2巡目ループのスタート地点
count_second=0#2巡目以降のループ
second_DP=[]

while(True):#スタート地点に戻ってきたら抜ける
  visited[ima_pos]=2#訪れたら更新
  mirai_pos=A[ima_pos]-1
  ima_pos=mirai_pos
  second_DP.append(ima_pos)
  count_second+=1#何回移動したか
  if ima_pos==second_start:
    break

#各DPには何番目(0から)スタートの町に行くか　が書かれている
if K<=count_first:
  print(first_DP[K-1])
elif K>count_first:
  cc=K-count_first
  if cc%count_second==0:
    print(second_DP[-1]+1)
  else:
    print(second_DP[cc%count_second-1]+1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
dic = {}
dic[1] = 1
new = 1
rest = 0
ball = 0
flag = False
for i in range(1, n + 1):
    new = a[new - 1]
    if new in dic:
        rest = dic[new] - 1
        ball = i - rest
        flag = True
        break
    else:
        dic[new] = i + 1
hoge = list(dic)
if flag:
    print(hoge[(k - (rest)) % ball + rest])
else:
    print(hoge[k - 1])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=[0]+list(map(int,input().split()))
pointer=1
visited=[1]
visittime=[0]
looplength=0
flag=0
for i in range(k-1):
    pointer=a[pointer]
    visited.append(a[pointer])
    visittime.append(i+1)
    if a[pointer] in visited:
        looplength=len(visited)
        print(visited[k%looplength])
        flag=1
        break
print(a[pointer] if flag==0 else"")

Submission status: Wrong Answer

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

j = 1
for i in range(k):
    now = a[j-1]
    if now in b:
        num = len(b) 
        start = b.index(now)
        duble = b[start:num]
        l = num - start
        num_two = len(duble)
        c = k - j
        d = c % num_two
        if d==0 or (d+1) == num_two:
            print(duble[0])
            break
        elif d==1:
            print(b[num-1])
            break
        else:
            print(duble[d])
            break  
    else:
        pass
    b.append(now)
    j = now
e = len(b)
if e == k + 1:
    print(b[k])
else:
    pass

Submission status: Wrong Answer

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

limit = K
now = 1
log = []
count = 1

while limit >= 0 and now not in log:
    if 1 not in log:
        log.append(1)
    #print("通過1",now,limit,log)
    now = A[now - 1]
    log.append(now)
    limit -= 1
    count += 1

if limit > 0:
    #print("通過2",now,limit,log)
    log2 = log[log.index(now):]
    limit = limit % len(log2)

while limit >= 0:
    #print("通過3",now)
    now = A[now - 1]
    limit -= 1

print(now)

Submission status: Wrong Answer

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


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    # Failed to predict input format
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    city = 1
    visited = {city: 0}
    cycle_len = 1

    for i in range(10**6):
        city = A[city - 1]
        visited[city] = i
        if visited.get(A[city - 1], False):
            offset = visited[A[city -1]]
            cycle_len = i
            break

    if abs(cycle_len - offset) != 0:

        K = (K - offset) % abs(cycle_len - offset)
    else:
        K = (K - offset)

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

    print(city)
    
    pass

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

point = 1
cnt = 1
m = 0
mm = 0
ind = 0
l = [1]
for i in range(n):
    point = a[point-1]
    cnt += 1
    if point in l:
        mm = i+1
        ind = l.index(point)
        m = cnt - 1 - ind
        break
    l.append(point)

print(l[(k-mm)%m+ind])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
L=list(map(int,input().split()))
ans=1
x=0
while x<=k:
  x=x+1
  ans=L[ans-1]
print(ans)

Submission status: Wrong Answer

Solution code:
def resolve():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    roop=0
    iti=0
    rireki=[]
    while roop==0:
        iti=a[iti]-1
        if iti in rireki:
            mae=rireki.index(iti)
            Mae=rireki[:mae]
            del rireki[:mae]
            roop=len(rireki)
            break
        rireki.append(iti)
    if k <= mae:
        print(Mae[k])
    else:
        k-=mae
        print(rireki[(k%roop)-1]+1)
resolve()

Submission status: Wrong Answer

Solution code:
n,m = map(lambda x: int(x), input().split())
a = [int(_) for _ in input().split()]

goal = 1
nexts = 1
visited = [1]
r_len = 1

for _ in range(m):
  nexts = a[nexts-1]
  if nexts in visited:
    r_len = len(visited[visited.index(nexts):])
    break
  else:
    visited.append(nexts)
  
rest = m-r_len+1
rec = rest%r_len
print(visited[r_len-rec-1])

Submission status: Wrong Answer

Solution code:
import sys

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

history =[1]
place = A[0]

for i in range(k-1):
  history.append(place)
  place = A[(int(place)-1)]
  if place == 1:
    amari = k % len(history)
    print(history[amari])
    sys.exit()

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)
    if loop ==1:
        ans =A[Z]
    else:        
        #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:
'''
.append(要素) リストに要素を追加
.extend(リスト) リストを連結する
.insert(場所,要素) 指定した場所に要素追加
del 配列名[場所]
-1で末尾で末尾から一つ前

sort()
sorted(reverse=true)

配列の初期化
配列名=[a]*n+[b]*m

Decimal()
'''

from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math
from functools import reduce
from operator import mul
from collections import Counter
import itertools
import fractions
import sys

t = [int(s) for s in stdin.readline().rstrip().split()]
n = t[0]
k = t[1]
Ak = [int(s) for s in stdin.readline().rstrip().split()]

data = [1]
tmp = 0
for el in Ak:
    data.append(Ak[tmp])
    tmp = Ak[tmp]-1
used = []
head = 0
mark = [int(s) for s in '0'*(n+1)]
for el in data:
    if (mark[el-1] == 1):
        head = el
        break
    mark[el - 1] = 1
    used.append(el)
key = used.index(head)
k -= key
print(used[key+k % (len(used) - key)])

Submission status: Wrong Answer

Solution code:
a,b=map(int,input().split())
lis=""
llis=[[] for i in range(a)]
c=[int(i) for i in input().split()]
j=0
while True:
    i=c[j]
    if len(llis[i-1])!=0:
        ans=lis.index(str(i))
        break
    lis+=str(i)
    llis[i-1].append(1)
    j=i-1
if ans+1>=b:
    print(lis[b-1])
else:
    lis=lis[ans:]
    print(lis[((b-ans)%len(lis))-1])

Submission status: Wrong Answer

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

c = 0
count= 0
now=1
old_now=1
flag = 0

while(c < K):
  now = A[now-1]
  c += 1
  if(C[now-1] == 1):
    for i in range(len(B)):
      if(now == B[i]):
        flag = 1
        count = i
        break
  if(flag == 1):
    break
  B.append(now)
  C[now-1] = 1
  old_now = now
if(c == K):
  print(now)
elif(old_now == now):
  print(now)
else:
  print(B[(K-count)%(len(B)-count)+count-1])

Submission status: Wrong Answer

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
    elif num == K:
        break
    else:
        B[num] = place
        C[place] = num
        D.add(place)
try:
    X = (K - num) % Y
    print(B[C[place] + X] + 1)
except:
    print(A[place]+1)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split(" "))
a_list = list(map(int,input().split(" ")))
visit = [0 for num in range(n)]
path = [0]
counter = 0
current_point = 0
while True:
    next_point = a_list[current_point]-1
    counter += 1
    if visit[next_point] == 1:
        current_point = next_point
        break
    visit[next_point] = 1
    path.append(next_point)
    current_point = next_point
loop_point = path.index(current_point)
loop_num = counter - loop_point
loop_path = path[loop_point:counter]
if loop_num == 0:
    print(loop_point+1)
elif k<loop_point:
    print(path[k+1])
else:
    print(loop_path[(k-loop_point)%loop_num]+1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
n, k = map(int,input().split())
a_list = list(map(int,input().split()))


visit_route = []#今までの道のり
visited_town = [0]*n#0=初めてきた、1=来たことがある
rooop = 0


def machi(x):
    global visit_route
    global visited_town
    global rooop
    if visited_town[x] == 1:
        rooop = x
        pass
    else:
        visited_town[x] += 1
        visit_route.append(x)
        machi(a_list[x]-1)

machi(0)
st = 0
for i in visit_route:
    st += 1
    if i == rooop:
        start = st
        break
tere = len(visit_route)
loop = tere - start +1

ans = (k - tere) % loop

#print(a_list)
#print(visit_route)
#print(start,loop,tere)
print(visit_route[start + ans-1]+1)

Submission status: Wrong Answer

Solution code:
# Your code here!
n,k = map(int,input().split())
a = list(map(int,input().split()))
ans = []
check = {}
key = -1
p = 0
while True:
    ans.append(p)
    check[p] = 0
    p = a[p]-1
    if p in check:
        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:
n,k = map(int,input().split())
a_list = list(input().split())
dum = a_list[0]
ans_list = ""
for i in range(1,k+1):
    k = k - 1
    ans_list = ans_list+dum
    dum = a_list[int(dum)-1]
    if ans_list.count(dum) == 1:
        break
#print(k)
#print(ans_list)
ind = ans_list.index(dum)
loop = ans_list[ind:]
len_loop = len(loop)
loop_after = k%len_loop
print(loop[loop_after-1])
#print(ans_list[1:])
#rint(ans_list)
#print(dum)
#print(ind)

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
    for i in range(N):
        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]

    print(res)



main()

Submission status: Wrong Answer

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

flag = [0]*(N+5) # 何回目に初めて訪れたか 
flag[0] = 1

tmp = 0
period = 1
period_pre = 0 # 周期が始まるまでのワープ回数
now = 0
for i in range(N):
  now = A[now]-1
  #print(now+1)
  #print(flag)
  #print()
  if(flag[now] != 0):
    period_pre = flag[now] 
    period = (i+2)-flag[now] 
    tmp = 1
    break
  flag[now] = i+2
if(tmp == 0):
  print(unnko)
  
#print('period',period)  
#print('period_pre',period_pre) 
if(period_pre >= K):
  num = period_pre
else:
  num = period_pre+((K-period_pre)%period)
#print('num',num)

now = 0
for i in range(num):
  now = A[now]-1
ans = now+1 # index→town_no  
print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
l=[]*n
for i in range(n):
    b=[0,0]
    b[0]+=i+1
    b[1]+=a[i]
    l.append(b)
c=0
ne=0
l1=[0]*n
while True:
    if c==k:
        print(l[ne][1])
        exit()
    ne+=-ne+l[ne][1]-1
    c+=1
    if l1[ne]==0:l1[ne]+=1
    else:
        break

roop_c=0
while True:
    if c+roop_c==k:
        print(l[ne][1])
        exit()
    if l1[ne]==1:l1[ne]+=1
    else:break
    ne+=-ne+l[ne][1]-1
    roop_c+=1

re=(k-c)%roop_c
if re==0:print(l[ne][0])
else:
    for i in range(re):
        if i==re-1:print(l[ne][1])
        ne+=-ne+l[ne][1]-1

Submission status: Wrong Answer

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

C = [0] * (N+1)
C[0] = 1

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

key = 0
for i in C:
    if C.count(i) == 2:
        key = i
        break

key_list = [i for i, x in enumerate(C) if x == key]
cycle = key_list[1]-key_list[0]

if K < key_list[0]:
    ans = C[K-1]
else:
    d = (K-key_list[0]) % cycle 
    ans = C[key_list[0] + d]

print(ans)

Submission status: Wrong Answer

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


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    # Failed to predict input format
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    city = 1
    visited = {city: 0}
    cycle_len = 1

    for i in range(N):
        city = A[city - 1]
        visited[city] = i
        if visited.get(A[city - 1], False):
            offset = visited[A[city -1]]
            cycle_len = i
            break

    if abs(cycle_len - offset) != 0:

        K = (K - offset) % abs(cycle_len - offset)
    else:
        K = (K - offset)

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

    print(city)
    
    pass

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np

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

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

route = [[1], [1]]

end = False
i = 0

while not end:
  if a[i] not in route[0]:
    route[0].append(a[i])
    i = a[i] -1
    route[1].append(1)
  else:
    position = route[0].index(a[i])
    # print(position)
    break

overhead = position
cycle_length = len(route[0]) - overhead

# print(route)
# print(overhead)
# print(cycle_length)

end_position = (k-overhead) % cycle_length
# print(end_position)

ans = route[0][overhead + end_position]

print(ans)

Submission status: Wrong Answer

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

list = [0]
next_A = 0
for i in range(len(A)):
    try:
        idx = list.index(A[next_A]-1)
        idx_max = len(list)
        break
    except:
        list.append(A[next_A] - 1)
        next_A = A[next_A] - 1

if len(list) == K:
    print(list[-1]+1)
else:
    fin_idx = (K-idx)%(idx_max -idx)
    print(list[idx+fin_idx]+1)

Submission status: Wrong Answer

Solution code:
import sys

def Destination(N, K, DestinationList, TravelHistory = [1] ):
    for Num in range(N):
        Destination = DestinationList[ TravelHistory[-1]-1]
        TravelHistory.append(Destination)
        if(Destination in TravelHistory[:-1]):
            Pos = TravelHistory[:-1].index(Destination)
            Period = len(TravelHistory)-Pos-1
            break;
    Times_K = (K-Pos)%Period
    #print(Pos, Period, Times_K, TravelHistory)
    Pos_K = TravelHistory[Pos+Times_K]
    return Pos_K


if(__name__ == '__main__'):
    In = input().split()

    N= int(In[0].strip())
    K= int(In[1].strip())

    DestinationList = []
    In = input().split()
    for Str in In:
        DestinationList.append( int(Str.strip()) ) # [M] -> value
    print(Destination(N, K, DestinationList) )

Submission status: Wrong Answer

Solution code:
def main():
	n, k = [int(x) for x in input().split(" ")]
	a = [int(x) for x in input().split(" ")]
	d = {}
	pos = 0
	step = 0
	cycle = False
	way = []
	while step < k and cycle == False:
		if pos in d:
			cycle = True
		else:
			d[pos] = step
			way.append(pos)
			pos = a[pos] - 1
			step += 1

	k -= step
	if k > 0:
		cycle = way[d[pos]:step]
		x = k % len(cycle)
		print(cycle[x] + 1)
	else:
		print(a[pos] + 1)

main()

Submission status: Wrong Answer

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

map = {}
for i in range(N):
    map[i+1] = A[i]

visited = {}
note = []
locate = 1
visited[1] = True
note.append(A[0])

i = 1
skippedFlg = False
while True:
    if i > K:
        break
    locate = map[locate]
    if locate in visited and not skippedFlg:
        # print("visitted!")

        diff = 0
        for j in range(len(note)-1,-1,-1):
            diff += 1
            if note[j] == locate:
                break

        i = i * (K // diff)
        skippedFlg = True
    else:
        visited[locate] = True
        note.append(locate)

    i += 1

print(locate)

Submission status: Wrong Answer

Solution code:
from math import *
from collections import *
from itertools import *
from bisect import *
from operator import *
def io():
    return map(int,input().split())
def op():
    return list(map(int,input().split()))
def o():
    return int(input())
def kl(con,x=0):
    if x==0:print('Yes') if con else print('No')
    elif x==1:print('yes') if con else print('no')
    elif x==2:print('YES') if con else print('NO')

MOD =    1000000007
MAX=2147483647
MIN=-2147483648
p=input
l,l1,l2,l3=[],[],[],[]
# for _ in range(o()):
n,k=io()
l=op()
x=y=0
i=0
while 1:
    if l[i] not in l1:
        l1.append(l[i])
        i=l[i]-1
    else:
        y=l1.index(l[i])
        x=len(l1)-y
        break
if k<=len(l1):
    print(l1[k-1])
else:
    k-=y
    k%=x
    print(l1[y+k-1])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
l = []
t = 1
for i in range(n):
    l.append(t)
    k -= 1
    if a[t - 1] in l:
        break
    t = a[t - 1]
i = l.index(a[t - 1])
k = k % (len(l)-i)
print(l[k+i])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
l=list(map(int,input().split()))
list=[l[0]]
num=0
while True:
  if l[list[num]-1] in list:
    break
  list.append(l[list[num]-1])
  num+=1
y=list.index(l[list[num]-1])
x=len(list)-y
ans=list[y:]
print(ans[(k-y)%x-1])

Submission status: Wrong Answer

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

limit = K
now = 1
log = []
count = 1

while limit >= 0 and now not in log:
    if 1 not in log:
        log.append(1)
    #print("通過1",now,limit,log)
    now = A[now - 1]
    log.append(now)
    limit -= 1
    count += 1

if limit >= 0:
    #print("通過2",now,limit,log)
    log2 = log[log.index(now):]
    limit = limit % len(log2)

while limit >= 0:
    #print("通過3",now)
    now = A[now - 1]
    limit -= 1

print(now)

Submission status: Wrong Answer

Solution code:

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

history = []
i = 0
now = 1
next_ = 0
while True:
  if now in history:
    break  
  else:
    history.append(now)
  
  next_ = A[now-1]
  now = next_
  i+=1

loop = history.index(now)
count = len(history[loop:])
K -= len(history) - count
K = K - (K//count)*count
print(history[loop:][K])

Submission status: Wrong Answer

Solution code:
'''
.append(要素) リストに要素を追加
.extend(リスト) リストを連結する
.insert(場所,要素) 指定した場所に要素追加
del 配列名[場所]
-1で末尾で末尾から一つ前

sort()
sorted(reverse=true)

配列の初期化
配列名=[a]*n+[b]*m

Decimal()
'''

from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math
from functools import reduce
from operator import mul
from collections import Counter
import itertools
import fractions
import sys

t = [int(s) for s in stdin.readline().rstrip().split()]
n = t[0]
k = t[1]
Ak = [int(s) for s in stdin.readline().rstrip().split()]

data = [1]
tmp = 0
for el in Ak:
    data.append(Ak[tmp])
    tmp = Ak[tmp]-1
used = []
head = 0
mark = [int(s) for s in '0'*(n+1)]
for el in data:
    if (mark[el-1] == 1):
        head = el
        break
    mark[el - 1] = 1
    used.append(el)
key = used.index(head)
k -= key
print(used)
print(mark)
print(used[key+k % (len(used) - key)])

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
d={}
l = list(map(int, input().split()))
for i in range(len(l)):
    d[i+1] = l[i]
print(d)

city = 1
l2 = [1]
while True:
    city = d[city]
    if city in l2:
        break
    l2.append(city)
first = l2.index(city)
if len(l2) <= k:
    if city == l2[-1]:
        print(city)
    else:
        l2 = l2[first:]
        print(l2[(k-first)%(len(l2))])
else:
    print(l2[k])

Submission status: Wrong Answer

Solution code:
N,K=(int(x) for x in input().split())
A=list(map(int, input().split()))
if K<=2*N:
    s=1
    for i in range(K):
        s=A[s-1]
    print(s)
else:
    s=1
    S={1}
    iloop=1
    while A[s-1] not in S:
        S.add(A[s-1])
        s=A[s-1]
        iloop=iloop+1
    p=s
    loop=1
    while A[s-1] != p:
        loop=loop+1
        s=A[s-1]
    g=(K-iloop)%loop+iloop
    s=1
    for i in range(g):
        s=A[s-1]
    print(s)
    print(iloop,loop,g)

Submission status: Wrong Answer

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


def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    li = [0]
    nt = 0
    for i in range(n):
        nt = a[nt]-1
        if nt == 0:
            break
        li.append(nt)

    x = k % len(li)
    # print(x)
    print(li[x]+1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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

    town = defaultdict(int)
    cn = defaultdict(int)
    
    visited = set()
    visited.add(0)
    cnt = 0
    tmp = A[0]-1
    town[cnt] = 0
    ii = 0
    
    while True:
        if(tmp not in visited):
            visited.add(tmp)
            cnt += 1
            cn[tmp] = cnt
            town[cnt] = tmp
            tmp = A[tmp]-1
        else:
            ii = cn[tmp]
            break
    if(K > len(town)):
        if(ii != 0):
            K -= ii
            ans = town[(K%(len(town)-ii))+ii]+1
        else:    
            ans = town[K%(len(town))]+1
        print(ans)
    else:
        ans = town[K]+1
        print(ans)
main()

Submission status: Wrong Answer

Solution code:
import sys
import itertools as iter
import math as m

def main():
    N, K = list(map(int, input().split()))
    A = [-1]
    A += [int(i) for i in input().split()]
    L = [0] * (N + 1)

    L[1] = 1
    x = A[1]
    L[x] = 1
    for i in range(K-1):
        x = A[x]
        if L[x] == 2:
            #print(L)
            lc = (K-i) % L.count(2)
            for _ in range(lc):
                x = A[x]
            print(A[x])
            return
        else:
            L[x] += 1
    print(x)
    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np

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

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

i = 0

k = k%n+1

tmp = l[0]
while i < (k-1) :
    tmp = l[tmp-1]
    i += 1
    
print(tmp)