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:
import sys
sys.setrecursionlimit(10000000)


def main():
    N, K = map(int, input().split())
    A = [0]
    B = [int(c) for c in input().split()]
    A.extend(B)
    dicts = {i: 0 for i in range(1, N + 1)}

    now = 1
    dicts[now] = 0
    num = 0
    while(num < K):
        now = A[now]
        num += 1
        if dicts[now] == 0:
            dicts[now] = num
            continue
        else:
            cycle = num - dicts[now]
            left = (K - num) % cycle
            K = left
            num = 0
    print(now)







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

reached=[1]
i=1
for k in range(n):
    if not A[i] in reached:
        reached.append(A[i])
        i=A[i]
    else:
        t1=reached.index(A[i])
        t2=k+1
        break
#print(reached)
ama=(k-t1)%(t2-t1)
#print(t1,t2,ama)
print(reached[t1+ama])

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

visited = [False] * N
loop = [0]
cur_town = 0
step = 0
while True:
    if visited[cur_town]:
        loop = loop[loop.index(cur_town):-1]
        step -= len(loop)
        print(loop[(K - step) % len(loop)] + 1)
        exit()
    else:
        visited[cur_town] = True
        cur_town = A[cur_town] - 1
        loop.append(cur_town)
        step += 1
        if step == K:
            exit()

Submission status: Wrong Answer

Solution code:
t = list(map(int,input().split()))
machi = list(map(int,input().split()))
next = machi[0]
for i in range(1,t[1]%t[0]):
  next = machi[next-1]
print(next)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
t=0
j=0
c=[]
b={}
for i in range(n):
    j=a[j]-1


    if j+1 in b:

        break
    c.append(j + 1)
    b[j + 1] = 1
m=c.index(a[c[-1]-1])
c=c[m:]

s=(k-m-1)%len(c)
print(c[s])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.insert(0, 0)
if a[1] == 1:
    print(1)
else:
    reached = {i: 0 for i in range(1, n+1)}
    now = 1
    count = 0
    while reached[now] == 0:
        reached[now] = count
        now = a[now]
        count += 1
    # print(reached, count)
    roop = count - reached[now]
    index = (k - reached[now]) % roop + reached[now]
    for key, value in reached.items():
        if value == index:
            print(key)
            break

Submission status: Wrong Answer

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

go = dict()
res = []

go[0] = True
res = [0]

now = a[0]
while True:
    if now in go:
        break
    res.append(now)
    go[now] = True
    now = a[now]

# 1
# [0, 1, 2, 3]
# (5 - 1) % (xunhuan)
amari = res.index(now)
xunhuan = res[amari:]
#print(res, xunhuan, amari)
if k <= amari:
    print(res[k])
else:
    print(xunhuan[ (k - amari) % len(xunhuan)] + 1)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
As = list(map(int,input().split()))
ugokikata = [1]
now = 1
for i in As:
    now = As[now-1]
    if now == ugokikata[0]:
        break
    ugokikata.append(now)
saigo = ugokikata[K % len(ugokikata)]
print(saigo)

Submission status: Wrong Answer

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

x=1
while x not in y:	
	y.append(x)
	x=l[x-1]
	
#	print(y)
	#c+=1
c=len(y)-y.index(x)
#print(c)
k=k%c
x=1
#print(c)
for i in range(k): 
	x=l[x-1]
print(x)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

count=[0]*(n+1)
cnt=0
i=1
while count[i]==0:
    count[i]=cnt
    if cnt==k:
        print(a[i])
        exit()
    cnt+=1
    i=a[i]

if cnt==k:
    print(a[i])
    exit()

#print(cnt,count)
#print("i",i)
loop=cnt-count[i]
#print("loop",loop)
goal=(k-cnt)%loop
#print(loop,goal)
if goal==0:
    print(i)
else:    
    print(count.index(count[i]+goal))

Submission status: Wrong Answer

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

ans=[]

j=0 #A進み
while A[j] not in ans:
    ans.append(A[j])
    j=A[j]-1
ans.append(A[j])

st=ans.index(A[j])
ans=ans[st:-1]
K-=st
l=len(ans)
print(ans)
print(ans[K%l-1])

Submission status: Wrong Answer

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

go = dict()
res = []

go[0] = True
res = [0]

now = a[0]
while True:
    if now in go:
        break
    res.append(now)
    go[now] = True
    now = a[now]

# 1
# [0, 1, 2, 3]
# (5 - 1) % (xunhuan)
amari = res.index(now)
xunhuan = res[amari:]
print(res, xunhuan, amari)
if k <= amari:
    print(res[k])
else:
    print(xunhuan[ (k - amari) % len(xunhuan)] + 1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

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

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

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

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

N, K = MII_split()
As = LII_split()

# search loop
visited = [False for _ in range(N)]
start = 1
visited[0] = True
loop = [start]
cur = start
for _ in range(N):
    nex = As[cur - 1]
    # print(cur)
    if not visited[nex - 1]:
        loop.append(nex)
        visited[nex - 1] = True
        cur = nex
    else:
        start_idx = loop.index(nex)
        before_num = start_idx
        loop = loop[start_idx:]
        break

# print(loop)
# return
K -= before_num
idx = K % len(loop)
print(loop[idx])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
tele=[0 for _ in range(n+1)]
cnt=1
v=1
while True:
    if tele[v]!=0:
        break
    else:
        tele[v]=cnt
        cnt+=1
        v=A[v-1]

circle_in=tele[v]
circle=[]
for idx,t in enumerate(tele):
    if t<circle_in:
        continue
    else:
        circle.append((t,idx))
circle.sort()

circle_len=len(circle)

if k<circle_in:
    ans=tele.index(k)
else:
    k=k-(circle_in-1)
    circle_idx=k%(circle_len)
    ans=circle[circle_idx][1]
    
print(ans)

Submission status: Wrong Answer

Solution code:
# 2020-05-10
n, k = map(int, input().split())
lst = list(map(int, input().split()))
ans = 1
a = k % n
for i in range(a+1):
    ans = lst[ans-1]
print(ans)

Submission status: Wrong Answer

Solution code:
inpl = lambda: list(map(int,input().split()))
N, K = inpl()
A = inpl()
for i in range(N):
    A[i] -= 1
P = dict()
k = 0
former = True
i = 1
while i <= K:
    if k in P.keys() and former:
        loop = i - P[k]
        K = i + (K-i) % loop
        former = False
    else:
        P[k] = i
        k = A[k]
    i += 1
else:
    print(k+1)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int, input().split()))
al = list(map(int, input().split()))
al = [a-1 for a in al]
used = [0]*n
first = [0]*n
step = 0
used[0] = 1
now = 0
for i in range(k):
    step += 1
    get = al[now]
    if used[get] == 0:
        first[get] = step
        used[get] = 1
        now = get
    else:
        dif = step-first[get]
        nokori = (k-step) % dif
        now = get
        for j in range(nokori):
            get = al[now]
            now = get
        print(now+1)
        exit()
print(now)

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

def dfs(index, root):
    root += [A[index]]

root = [1]
index = 0

while True:

    if A[index] in root:
        hoge = root[root.index(A[index]):]
        ho = root.index(A[index])
        break

    root += [A[index]]
    index = A[index] - 1

nokori = (K-ho) % len(hoge)

print(hoge[nokori])

Submission status: Wrong Answer

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

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

graph = []

time = [-1] * N

for i in range(N):
    graph.append([i, A[i]])

now = 0
nex = 0
time[0] = 0
loop = 0

while True:
    now = nex
    nex = A[now] - 1

    if time[nex] == -1:
        time[nex] = time[now] + 1
    else:
        loop = nex
        break

if K > max(time):
    K %= (max(time) - time[loop] + 1)

for i in range(N):
    if time[i] == K:
        print(i + 1)

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    def int_0(num):
        return int(num) - 1

    N, K = map(int, input().split())
    A = tuple(map(int_0, input().split()))
    
    # dfs
    INF = 10 ** 18
    visited = [False] * N
    dist = [INF] * N
    info  = {}
    def dfs(s):
        stack = deque()
        stack.append(s)
        visited[s] = True
        dist[s] = 0
        while stack:
            now = stack.pop()
            visited[now] = True
            nv = A[now]
            if visited[nv] == True:
                info["start"] = nv
                info["length"] = dist[now] - dist[nv] + 1
                info["f"] = dist[nv]
                break
            else:
                dist[nv] = dist[now] + 1
                stack.append(nv)
    dfs(0)

    K -= info["f"]
    K %= info["length"]

    now = info["start"]
    for _ in range(K):
        now = A[now]
    print(now+1)




    



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k=[int(x) for x in input().split()]
p=[(int(x)-1) for x in input().split()]
a=[0]
i=0
while p[i] not in a:
  a.append(p[i])
  i=p[i]
l=a.index(p[i])
if k<=l: print(a[k])
else: print(1+a[l+(k-l)%(len(a)-l)])

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()


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

    pos = A[1]
    visited = {1}
    while pos not in visited:
        visited.add(pos)
        pos = A[pos]
    
    start = pos
    loop = 1
    pos = A[pos]
    while pos != start:
        pos = A[pos]
        loop += 1
    
    dist = 0
    pos = 1
    while pos != start:
        pos = A[pos]
        dist += 1

    #print("dist={}, loop={}".format(dist, loop))
    
    if dist < K:
        K -= dist
        K %= loop
    pos = start
    for _ in range(K): pos = A[pos]
    print(pos)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

ls = [1]
cnt = 0
while(1):
    t = A[ls[-1]-1]
    if t in ls:
        nls = ls[ls.index(t):]
        break
    else:
        ls.append(A[ls[-1]-1])
        cnt += 1
        
nokori = K-cnt-1
amari = nokori % len(nls)
print(nls[amari])

Submission status: Wrong Answer

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


def answer():
    path = [1]
    visited = set([1])
    now = 1
    t = 0

    while True:
        if now == a[now - 1]:
            return now

        now = a[now - 1]
        t += 1

        if now in visited:
            ti = path.index(now)
            tc = t - ti
            cycle = path[ti:]
            break
        else:
            path.append(now)
            visited.add(now)

    return cycle[(k - t) % tc]


print(answer())

Submission status: Wrong Answer

Solution code:
from collections import deque

N, K = map(int, input().split())
A = list(map(int, input().split()))
T = set([0])  # 0-indexed

c = 0  # 0-indexed
for i in range(N + 1):
    c = A[c] - 1
    # print('c', c)
    if c not in T:
        T.add(c)
    else:
        break
C = deque([c])
T = set([c])  # 0-indexed
for i in range(N + 1):
    c = A[c] - 1
    # print('c', c)
    if c not in T:
        T.add(c)
        C.append(c)
    else:
        break
c2 = 0  # 0-indexed
i = 0
for i in range(N + 1):
    c2 = A[c2] - 1
    if c2 == c:
        break
# print(C)
# print('len(C), i', len(C), i)

if C[0] == 0:
    mod = K % len(C)
    ans = C[mod]
else:
    mod = (K - (i + 1)) % len(C)
    ans = C[mod]
print(ans + 1)

Submission status: Wrong Answer

Solution code:
x=input().split()
n=int(x[0])
k=int(x[1])
a=list(map(int,input().split(" ")))
place=1
if n>=k:
  for _ in range(n):
    place=a[place-1]
  print(place)
else:
  check=False
  lists=[1]
  while check==False:
    if a[place-1] in lists:
      check=True
      p=lists.index(a[place-1])
    else:
      lists.append(a[place-1])
      place=a[place-1]
  print(lists[p+(k-p)%(len(lists)-p)])

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

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

went={i:0 for i in range(1,n+1)}

now=1
cnt=1
for i in range(n+1):
    if went[now]>0:
        t=cnt-1
        s=went[now]
        break
    else:
        went[now]=cnt
        now=A[now-1]
        cnt+=1

val=((k+1-t)%(t-s+1)-1)%(t-s+1)+s
for ele in went:
    if went[ele]==val:
        print(ele)
        break

Submission status: Wrong Answer

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

kaisuu = k % n

ans = a[kaisuu-1]
print(a[ans-1])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = [int(x) for x in input().split()]
num = 0
for _ in range(k):
    num = a[num-1]
print(a[num-1])

Submission status: Wrong Answer

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

exist = [a[0]]

cnt = 1
while(True):
    if a[exist[-1]-1] in exist:
        idx = exist.index(a[exist[-1]-1])
        exist.append(a[exist[-1]-1])
        break
    exist.append(a[exist[-1]-1])
    cnt += 1

#k = k-idx
#print(idx,exist,cnt)
d = (k-idx) % (cnt-idx)

print(exist[d+idx-1])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
move = [a[i] - 1 for i in range(n)]
#print(move)
d = [-1 for _ in range(n)]
d[0] = 0
cur = 0
for _ in range(300000):
    to = move[cur]
    if d[to] == -1:
        d[to] = d[cur] + 1
    else:
        rou = d[cur] + 1 - d[to]
        rou_start = to
        break
    cur = to
#print(rou_start, rou)
#print(d)
if k < d[rou_start]:
    x = k
else:
    x = (k - d[rou_start]) % rou
cur = rou_start
for _ in range(x):
    cur = move[cur]


print(cur + 1)

Submission status: Wrong Answer

Solution code:
n,k,*a=map(int,open(0).read().split())
b=[1]
for i in range(n):
  if a[b[-1]-1] in b:
    idx=b.index(a[b[-1]-1])
    break
  else:
    b.append(a[b[-1]-1])
mod=len(b[idx:])
d=len(b[:idx])
print(b[d+(k-d)%mod])

Submission status: Wrong Answer

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

already = [False for i in range(N)]
already[0] = True
tel = [0]

while True:
    tel.append((tmp := A[tel[-1]]))
    
    if already[tmp]:
        tel.pop()
        break
        
    already[tmp] = True

for i in range(len(tel)):
    if tel[i] == tmp:
        s = i
        break

ans = (K - s) % (len(tel) - s)
print(tel[ans + s] + 1)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, k = map(int, readline().split())
a = list(map(int, readline().split()))
dict = [False] * (n + 1)
now = a[0]
for i in range(1, n * 2):
    if i == k:
        print(now)
        exit()
    now = a[now - 1]
    if dict[now]:
        k -= i
        dict = [False] * (n + 1)
        dict[now] = True
        check = a[now - 1]
        for j in range(1, n * 2):
            now = a[now - 1]
            if dict[now]:
                if j != 1:
                    k %= j
                    k += 1
                break
            else:
                dict[now] = True
        break
    else:
        dict[now] = True
now = check
for i in range(k):
    now = a[now - 1]
print(now)

Submission status: Wrong Answer

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

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

k = k % n
ne = 1

for i in range(k+1):
  count = a[ne-1]
  ne = a[i]

print(count)

Submission status: Wrong Answer

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

done = [0]*N
now = 0
cnt = 1
while True:
    if done[now] != 0:
        start = done[now] - 1
        cycle = cnt - start - 1
        break
    else:
        done[now] = cnt
        now = A[now]-1
        cnt += 1
if K>=start:
    K -= start
K %= cycle
for _ in range(K):
    now = A[now]-1
print(now+1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from typing import Dict, List, Optional, Set, Tuple


def solve(values: List[int], nb: int) -> int:
    seen = {}
    cur = 0
    move = 0
    while move < nb and cur not in seen:
        seen[cur] = move
        move += 1
        cur = values[cur] - 1
    if move == nb:
        return cur
    cycle_length = move - seen[cur]
    _nb_cycles, rest = divmod(nb - move, cycle_length)
    LOG.debug((cur, cycle_length, move, seen))
    for _ in range(rest):
        cur = values[cur] - 1
    return cur + 1


def do_job():
    "Do the work"
    LOG.debug("Start working")
    N, K = map(int, input().split())
    values = list(map(int, input().split()))
    assert len(values) == N
    result = solve(values, K)
    print(result)


def print_output(testcase: int, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result))


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    do_job()
    return 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())


class memoized:
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.
    """

    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        try:
            return self.cache[args]
        except KeyError:
            value = self.func(*args)
            self.cache[args] = value
            return value
        except TypeError:
            # uncachable -- for instance, passing a list as an argument.
            # Better to not cache than to blow up entirely.
            return self.func(*args)

    def __repr__(self):
        """Return the function's docstring."""
        return self.func.__doc__

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

Submission status: Wrong Answer

Solution code:
n, k = map(int,input().split())
town = list(map(int,input().split()))
cnt = 1
step = 1
now = town[0]
via = [1]
while((now not in via)&(step<=n)):
  via.append(now)
  now = town[now -1]
  cnt += 1
  step += 1

loop = via[via.index(now):]
print(loop[(k - cnt)%len(loop)])

Submission status: Wrong Answer

Solution code:
def mp():return map(int,input().split())
def lmp():return list(map(int,input().split()))

n,k = mp()
a = lmp()
a.insert(0,0)
here = 1
cnt = 0
hajimete = [0]*(n+1)
used = set()
used.add(1)
flag = False
for i in range(k):
    cnt += 1
    here = a[here]
    if here not in used:
        used.add(here)
        hajimete[here] = cnt
    else:
        flag = True
        break
if not flag:
    print(here)
else:
    loop = cnt - hajimete[here]
    town = hajimete[here] + ((k-hajimete[here]) % loop)
    print(hajimete.index(town))

Submission status: Wrong Answer

Solution code:
data = input().split()
n = int(data[0])
k = int(data[1])
t = list(map(int,input().split()))

p = t[0]
for _ in range(k):
    p = t[p-1]
print(t.index(p)+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

v = 0
li = [v]
set_ = {v}
while True:
    nxt_v = a[v]
    if nxt_v not in set_:
        li.append(nxt_v)
        set_.add(nxt_v)
        v = nxt_v
    else:
        start = nxt_v
        break


for i in range(len(li)):
    if li[i] == start:
        ratio = li[i:]
        syoko = li[0:i]

if k < len(syoko):
    print(syoko[k])

else:
    k -= len(syoko)
    print(ratio[k % len(ratio)] + 1)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10**7)
def run():
    N,K = map(int, sysread().split())
    A = [0] + list(map(int, sysread().split()))
    perm = [1, A[1]]
    seen = [[-1, False] for _ in range(N+1)]
    seen[1], seen[A[1]] = [1,True], [2,True]
    l = 2
    while True:
        v = perm[-1]
        idx, boo =  seen[A[v]]
        if boo:break
        l += 1
        perm.append(A[v])
        seen[A[v]] = [l,True]

    K -= idx - 1
    perm = perm[idx-1:]
    print(perm[K % len(perm)])



if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
def main():
    n,k=map(int,input().split())
    a=list(map(int,input().split()))
    cnt=0
    b=[1]
    res=[-1]*n
    res[0]=0
    flg=0
    now=1
    start=0
    t=0
    while flg==0:
        cnt+=1
        if res[a[now-1]-1]==-1:
            res[a[now-1]-1]=cnt
            b.append(a[now-1])
            now=a[now-1]
        else:
            t=cnt-res[a[now-1]-1]
            start=res[a[now-1]-1]
            k-=start
            flg=1
    print(b[start+(k%t)])
if __name__=="__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
t=0
j=0
c=[]
b={}
for i in range(n):
    j=a[j]-1


    if j+1 in b:

        break
    c.append(j + 1)
    b[j + 1] = 1
m=c.index(a[c[-1]-1])
c=c[m:]
print(c)
s=(k-m-1)%len(c)
print(c[s])

Submission status: Wrong Answer

Solution code:
def binarySearch (arr, l, r, x): 
  
    # Check base case 
    if r >= l: 
  
        mid = l + (r - l) // 2
  
        # If element is present at the middle itself 
        if arr[mid] == x: 
            return mid 
          
        # If element is smaller than mid, then it  
        # can only be present in left subarray 
        elif arr[mid] > x: 
            return binarySearch(arr, l, mid-1, x) 
  
        # Else the element can only be present  
        # in right subarray 
        else: 
            return binarySearch(arr, mid + 1, r, x) 
  
    else: 
        # Element is not present in the array 
        return -1
n,k=map(int,input().split( ))
s=input().split( )
p=[]
g=0
while binarySearch(p,0,len(p)-1,int(g))==-1:
    p.append(int(g))
    g=int(s[int(g)])-1
k+=1
x=p.index(g)
y=len(p)
if k>=y:
    u=p[x:y]
    k-=x
    v=(k)%(y-x)
    print(u[v-1]+1)
else:
    print(p[k]+1)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split(' '))
a=list(map(int,input().split(' ')))
loc=1
begin=0
end=0
d={}
for i in range(n):
    loc=a[loc-1]
    if loc in d.keys():
        begin=d[loc]
        end=i+1
        break
    d[loc]=i+1
if end !=0:
    k=(k-begin+1)%(end-begin)+begin-1
loc=1
for j in range(k):
    loc=a[loc-1]
print(loc)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)
n , k = map(int , input().split())
arr = list(map(int , input().split()))
dic = defaultdict(int)
for i in range(1,n+1):
	dic[i] = arr[i-1]
cycle = []
def dfs(node):
	if node in cycle:
		return node
	else:
		cycle.append(node)
		k = dfs(dic[node])
	return k
cyind = dfs(1)
#print(cycle, cyind)
csize = len(arr[cyind:])
if k >= cyind - 1: k -= cyind - 1
else: 
	count = 0
	curr = 1
	while count != k:
		curr = dic[curr]
		count+=1
	print(curr); exit()
k %= csize
count = 0
curr = 1
#print("k " , k)
while count != k:
	curr = dic[curr]
	count+=1
print(curr)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
towns = [int(s) for s in input().split()]
pos = []
pos_set = set()
cur = towns[0]

while not cur in pos_set:
    pos.append(cur)
    pos_set.add(cur)
    cur = towns[cur-1]
    
j = pos.index(cur)
print(pos[(k-j-1)%(len(pos)-j) + j])

Submission status: Wrong Answer

Solution code:
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
def resolve():
    N, K = lr()
    A = lr()
    vis = [-1]*(N+1)
    dis = [0]*(N+1)
    v = 1
    cnt = 0
    while vis[v] == -1:
        dis[cnt] = v
        vis[v] = cnt
        v = A[v-1]
        cnt += 1
    print(dis[K%(cnt-vis[v])])
resolve()

Submission status: Wrong Answer

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

root = []
i = 0
flag = False
while a[i] not in root:
    root.append(a[i])
    i = a[i] - 1
    if a[i] == root[0]:
        flag = True
s_i = root.index(a[i])
if k <= i or flag:
    print(root[k % len(root) - 1])
else:
    print(root[(k - s_i) % (len(root) - s_i)])

Submission status: Wrong Answer

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

import sys
n = N - 1
idists = [d - 1 for d in dists]
visits = [-1] * N

# 手レポーターがループしてる部分を探す
now = 0
count = 0
while True:
#     print(now, visits)
    if visits[now] >= 0:
        break
    visits[now] = count
    now = idists[now]
    if count == K:#早く着いちゃった
        print(now + 1)
        sys.exit()
    count += 1

# ループを端折る
cycle = count - visits[now]
rest = (K - count) % cycle
for _ in range(rest):
#     print(" ", now)
    now = idists[now]
print(now + 1)

Submission status: Wrong Answer

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

move_dic = {1:0}
move_list = [1]
pre = A[0]
counter = 0
while True:
    if pre in move_dic:
        loopstart = move_dic[pre]
        loop = move_list[loopstart:]
        init_len = len(move_list)
        loop_len = len(loop)
        break
    else:
        counter += 1
        move_dic[pre] = counter
        move_list.append(pre)
        pre = A[pre - 1]

ans = (K - init_len) % loop_len
print(loop[ans])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = [int(i)-1 for i in input().split()]
loc = 0
lst = [False]*n
lst[0] = True
while True:
    if lst[a[loc]]:
        x = a[loc]
        break
    loc = a[loc]
    lst[loc] = True
cnt = 0
loc = 0
while True:
    loc = a[loc]
    cnt += 1
    if loc == x: break
cnt2 = 0
while True:
    loc = a[loc]
    cnt2 += 1
    if loc == x: break
k -= cnt2
k %= cnt
loc = x
while k > 0:
    loc = a[loc]
    k -= 1
print(loc+1)

Submission status: Wrong Answer

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

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

memo = [0]*(n+1)

for i in range(n):
    memo[i+1] = t[i]

move = 1

count = 0

check = [0]*(n+1)

while check[move] == 0 and count < k:
    check[move] += 1
    move=memo[move]
    count += 1

if k == count:
    print(memo[move])
else:
    count2 = 0
    check = [0]*(n+1)
    move_log = []
    while check[move] == 0:
        move_log.append(move)
        check[move] += 1
        move=memo[move]
        count2 += 1
    print(move_log[(k-count)%count2])