Problem:


Score: 400 points

Problem Statement

The Kingdom of Takahashi has N towns, numbered 1 through N.

There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.

Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Help the king by writing a program that answers this question.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2



Sample input:
4 5
3 2 4 1


Sample output:
4

Submission status: Runtime Error

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline




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


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact



def search(x,step,vnode):
    global L,visited
    
    #print(visited,x)
    visited[x]=step
    vnode.append(x)
    if visited[L[x]]>=0:
        C=step+1-visited[L[x]]
        k=(K-visited[L[x]])%C
        
        #print(k)
        #print(vnode)
        #print(k,L[x],visited[L[x]])
        print(vnode[visited[L[x]]+k])
               
        #print(step,x,visited)
        sys.exit(0)
        return
    
    
    search(L[x],step+1,vnode)
    
    
    

N,K=acinput()
L=[0]
L.extend(acinput())

visited=[-1]*(N+1)
#visited[1]=1
search(1,0,[])

Submission status: Runtime Error

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

dist = A[0]
visited = {1}
_v = [1]
stop = 0
for _ in range(10**7+1):
    if dist in visited:
        stop = dist
        break
    visited.add(dist)
    _v.append(dist)
    dist = A[dist-1]

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

loop = len(_v) - made
_v = _v[made:]

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

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

Submission status: Runtime Error

Solution code:
n,k = (int(x) for x in input().split())
town = [int(i) for i in input().split()]
warp  = [1]
checklist = [0]+[-1]*n
i = 0
j = 0
while j<=n:
    #print(town[i])
    warp.append(town[i])
    #print(warp,checklist)
    if checklist[town[i]-1]!=-1:
        s = checklist[town[i]-1]
        warp = warp[s:j]
        #print(checklist[town[i]-1],j)
        #print("a",warp)
        break
    checklist[town[i]-1] = j
    i = town[i]-1
    j += 1


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

Submission status: Runtime Error

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

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

k = k % n + 1
ne = 0

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

print(ne)

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
import numpy as np
link = set()
next = a[0]
link.add(1)
while next not in link:
    link.add(next)
    next = a[next-1]
# print(next)
# print(list)

link2 = set()
next2 = a[0]
link2.add(1)
while next not in link2:
    link2.add(next2)
    next2 = a[next2-1]

ans = 0
rep = len(link)+1-len(link2)
# print(rep)
if(k > len(link2)-1):
    p = (k-len(link2)+2)%rep
    # print(p)

    # print(next)
    for i in range(len(link)-1):
        next = a[next]
else:
    for i in range(k):
        next = a[0]

ans = next
print(ans)

# for i in range(p):

Submission status: Runtime Error

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

l = []
used = [0 for _ in range(n)]

c = 0
flag = True
while 1:
    if flag:
        flag = False
    else:
        l.append(c)
    if used[c] == 1 and l:
        break
    used[c] = 1
    c = a[c]

p = 0
for i in range(len(l)):
    if l[i] == l[-1]:
        l = l[i:-1]
        p = i
        break

print(l[(k-p)%len(l)-1]+1)

Submission status: Runtime Error

Solution code:
import itertools
from collections import defaultdict
import collections
import sys
sys.setrecursionlimit(200000)
mod = 1000000007

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

tf = [False] * (n + 1)
tf[1] = True
ss = [1]
cnt = 0
while cnt < n ** 2:
    if len(ss) != 1 and tf[a[ss[cnt] - 1]]:
        d = a[ss[cnt] - 1]
        break
    tf[a[ss[cnt] - 1]] = True
    ss.append(a[ss[cnt] - 1])
    cnt += 1

if len(ss) >= k:
    print(ss[k])
else:
    print(ss[ss.index(d)+(k -len(ss)) % (len(ss) - ss.index(d))])
    # print(ss.index(d))
    # print(ss[k % (len(ss) - ss.index(d))])

Submission status: Runtime Error

Solution code:
class Telp:
    def __init__(self, to, idx):
        self.to = to
        self.idx = idx
        self.visited = False
        self.step = -1

    def visit(self, step):
        self.visited = True
        self.step = step

    def is_visited(self):
        return self.visited


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

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

net = {}

for i in range(n):
    net[i] = Telp(a[i], i)

current = net[0]
count = 0
path = [0]

while not current.visited:
    # print(current.to)
    current.visit(count)
    current = net[current.to - 1]
    path.append(current)
    count += 1
    # print("count", count)

offset = current.step
loop = count - offset
fact_idx = (k - offset) % loop

# print("count, offset, loop, fact_idx", count, offset, loop, fact_idx)
# print("ans", path[offset + fact_idx - 1].to)

print(path[offset + fact_idx - 1].to)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

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

visitcount = dict()
n_point = list()

x = 1
count = 0
while(x not in set(visitcount)):
  visitcount[x] = count
  n_point.append(x)
  x = A[x-1]
  count += 1
  
period = count - visitcount[x]

if (K < visitcount[x]):
  print(n_point[K])
else:
  y = (K-visitcount[x]) % period
  print(n_point[visitcount[x] + y])

Submission status: Runtime Error

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

hist = [0 for i in range(N)]
route = []
loop = []

jump = 1
cur = A[0] - 1
route.append(0)
hist[0] = jump
while hist[cur] == 0:
    jump = jump + 1
    route.append(cur)
    hist[cur] = jump
    cur = A[cur] - 1

loop = route[cur:]

if K < len(route):
    print(route[K] + 1)
else:
    K = K - len(route) - 1
    K = K % len(loop)
    print(loop[K] + 1)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush

from decimal import *

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

##### 割り算の切り上げ #####
# tmp = -(-4 // 3)

##### dict の for文 #####
# for k, v in d.items():
#     print(k, v)

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	N,K = inputMap()
	A = inputList()

	mati = [0 for i in range(N)]
	for i,val in enumerate(A):
		mati[i] = val-1

	tugi = 0
	gizi = []
	ans = []
	cnts = 0
	flg = False
	for i in range(K):
		tugi = mati[tugi]
		if flg == False:
			cnts += 1
			if tugi in gizi:
				flg = True
				ans.append(gizi[-1])
				ans.append(tugi)
			else:
				gizi.append(tugi)
		else:
			if tugi in ans:
				break
			else:
				ans.append(tugi)

	tmp = len(ans)
	cnts = cnts - len(ans)
	kotae = (K-cnts+1) % (tmp)

	#print(cnts)
	#print(kotae)
	#print(ans)
	print(ans[kotae]+1)


#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# N 個のボールを K グループに分ける場合のパターン数
def sunuke(N, K, mod=10**9+7):
	if N < K or K-1 < 0:
		return 0
	else:
		return combination(N-1, K-1, mod)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)


class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# dfs のサンプル
def dfs(graph,parent,counter,edge):
    stk = []
    stk.append(edge)
    while len(stk) > 0:
        p = stk.pop()
        for e in graph[p]:
            if parent[p] == e:
                continue
            else:
                parent[e] = p
                counter[e] += counter[p]
                stk.append(e)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
	main()

Submission status: Runtime Error

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

arr = [1]
cnt = 1

ans = [0 for i in range(N+1)]
ans[0] = 1

for i in range(N):
  if i == 0:
    s = List[i]
    arr.append(s)
    ans[s] += 1
  else:
    if ans[s-1] == 1:
      b = arr.index(List[s-1])
      break
    else:
      s = List[s-1]
      arr.append(s)
      ans[s] += 1
      
l = len(arr)
c = int( (K-b) % (l-b) )

if K-b > 0:
  print(arr[b+c])
else:
  print(arr[K-1])

Submission status: Runtime Error

Solution code:
max = int(data[1])
limit = max
times = 0
pos = 1
experience = [1]
while max > 0:
    pos = telepo[pos - 1]
    max -= 1
    times += 1
    #print(pos)
    if pos in experience:
        length = len(experience) - experience.index(pos)
        max = max % length
        if max == 0:
            break
        while max > 0:
            pos = telepo[pos - 1]
            max -= 1
            times += 1
            #print(pos)
        break
    experience.append(pos)
print(pos)

Submission status: Runtime Error

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

# ループの値を取得
work = 1
a_set = set()
loop_start_num = 0
loop_start_count = 0
for _ in range(K):
    work = A[work - 1]
    if work in a_set:
        loop_start_num = work
        break
    else:
        a_set.add(work)
        loop_start_count += 1

loop_start_index = A.index(loop_start_num)

work = loop_start_num
count = 0
a_list = []
for _ in range(K):
    work = A[work - 1]
    if work in a_list:
        break
    else:
        a_list.append(work)
        count += 1
#print(a_list, count)
print(a_list[(K - loop_start_count + 1) % count])

Submission status: Runtime Error

Solution code:
root = list()


def dfs(A, num, N):
    if A[num] in root:
        return root.index(A[num])
    else:
        root.append(A[num])
        return dfs(A, A[num]-1, N)


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

    start = dfs(A, 0, N)

    if K <= len(root):
        print(root[K-1])
    else:
        index = (K - start) % (len(root)-start)
        loop = root[start:]
        print(loop[index-1])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
visit = [-1 for i in range(n)]
root = []
now = 1
length = 0
root.append(now)
if k > n:
    for i in range(n):
        if visit[now - 1] != 1:
            visit[now - 1] = 1
            now = a[now - 1]
            root.append(now)
            length += 1
        else:break
    start = 0
    for i in range(n):
        if root[i] == now:
            start = i
            break
    length -= start + 1
    k -= start
    k %= length
    ans = root[start]
    for i in range(k):
        ans = root[start + i]
    print(ans)
else:
    for i in range(k):
        now = a[now - 1]
    print(now)

Submission status: Runtime Error

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

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

fumi = set([0])
start = None
end = None
aab = [0]
for i in range(2*10**5):
    next = aa[aab[-1]] - 1
    if next in fumi:
        if start is None:
            start = i
            fumi = set()
        else:
            end = i
            break
    aab.append(next)
    fumi.add(next)

random_first = len(aab) - 2*(end - start)
#print(aab, start, end, aab[start+1:end+1], aab[:random_first])

first = aab[:random_first]
one_cicle = aab[start+1:end+1]
if k <= len(first):
    print(first[k]+1)
else:
    k = k-len(first)
    print(one_cicle[k%len(one_cicle)]+1)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
f = [0 for _ in range(n)]
f[0] = 1

v = [0]
s = 0
idx = 0
loop = 0
last = 0

for _ in range(k):
    vi = a[last] - 1
    if not f[vi]:
        f[vi] = 1
        last = vi
        s += 1
        v.append(vi)
    else:
        s += 1
        idx = v.index(vi)
        loop = s - idx
        break

remain = k - s

print(v[idx:][remain % loop] + 1)

Submission status: Runtime Error

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

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

f(A[0])
# print(l)
# print(visited)
a = [i for i, x in enumerate(visited) if x == kaburi]
b = visited[a[0]:a[1]]
# print(b)
# print(l)
print(b[(K-a[0])%(l-a[0])])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = set()
s.add(1)
former = []
latter = []
temp = [1]
idx = 0
cur = a[idx]
buf = 0

while True:
    if cur not in s:
        s.add(cur)
        temp.append(cur)
        cur = a[cur-1]
    else:
        buf = temp.index(cur)
        former = temp[:buf]
        latter = temp[buf:]
        break

# print('buf:', buf)
# print('former:', former)
# print('latter:', latter)

if k <= len(former):
    print(former[k])
else:
    mod = k % len(latter)
    # print('mod:', mod)
    idx = mod - len(former)
    print(latter[idx])

Submission status: Runtime Error

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

arr = [-1]*n
next_town = 0
arr[0] = 0
flag = False
for i in range(1, k+1):
    print(next_town+1)
    next_town = a[next_town] - 1
    if arr[next_town] >= 0:
        flag = True
        x = i - arr[next_town]
        l = arr[next_town]
        break
    else:
        arr[next_town] = i
print(flag, x, k%x)
if flag == False:
    print(next_town+1)
else:
    for i in range((k-l)%x):
        print(next_town+1)
        next_town = a[next_town] - 1

    print(next_town+1)

Submission status: Runtime Error

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

dist = A[0]
visited = {1}
_v = [1]
stop = 0
for _ in range(10**5+1):
    if dist in visited:
        stop = dist
        break
    visited.add(dist)
    _v.append(dist)
    dist = A[dist-1]

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

loop = len(_v) - made
_v = _v[made:]

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

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

Submission status: Runtime Error

Solution code:
def calc(i, k):
    ans_list = [i]
    ans_set = set([i])
    count = 1
    i = a[i]
    while (i not in ans_set) & (count < k):
        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, k)
if count < k:
    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:
    print(ans_list[-1] + 1)

Submission status: Runtime Error

Solution code:
from collections import deque
N,K = map(int,input().split())
A = [0] + list(map(int,input().split()))
G = dict([(i,[]) for i in range(1,N+1)])
for i in range(1,N+1):
  G[i].append(A[i])

l = deque([A[1]])
seen = [False for i in range(N+1)]
seen[1] = True
d = [0 for i in range(N+1)]
d[A[1]] = 1
for i in range(K):
  v = l.popleft()
  if seen[v] != True:
    seen[v] = True
    l.append(A[v])
    if seen[A[v]] == True: 
      a = d[A[v]]
      b = d[v] + 1 - a
    else:  
      d[A[v]] = d[v] + 1
  else:  
    start = v
    break

kaisu = (K-a)%b
p = start
for i in range(kaisu):
  p = A[p]
print(p)

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
a = [int(x) for x in input().split()]
nn = n
for i,aa in enumerate(a):
    
    if i+1 == aa:
        nn -= 1
m = k%nn

before = 0
after = 1
for i in range(m):
    after = a[after-1]
print(after)

Submission status: Runtime Error

Solution code:
import logging

logging.basicConfig(level=logging.INFO, format="%(message)s")
#logging.disable(logging.CRITICAL)


def main():
    N, K = map(int, input().split())
    A_i = list(map(int, input().split()))
    B_i = []
    cycle_list = []
    
    cycle = 0
    diff = 0
    counter = 0
    machi = 1
    for num in A_i:
        if machi in B_i:
            diff = B_i.index(machi)
            cycle = counter - diff
            cycle_list = B_i[diff:]
        else:
            counter += 1
            machi = A_i[machi - 1]

    mod_K = (K - diff) % cycle

    print(cycle_list[mod_K])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
#from functools import lru_cache   #use @lru_cache(None)
if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')
#
def input(): return sys.stdin.readline()
def mapi(arg=0): return map(int if arg==0 else str,input().split())
#------------------------------------------------------------------


n,k = mapi()
a = [0]+list(mapi())
gr = defaultdict(int)
for i in range(1,n+1):
    gr[i]=a[i]

vis ={}
path = []
p = 1
def dfs(s):
    global p
    if s in vis:
        p = s
        return
    path.append(s)
    vis[s] = 1
    dfs(gr[s])
dfs(1)
i = 0
ln = 0
path2 = path[:]
while i<len(path):
    if p==path[i]:
        path2 = path2[i:]
        break
    i+=1
#print(path)
if k<len(path)-len(path2):
    print(path[k])
else:
    k -= len(path)-len(path2)
    print(path2[k%len(path2)])
#print(dfs(1,k))

Submission status: Runtime Error

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

Submission status: Runtime Error

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

m = [0 for i in range(n)]
m[0] = 1
l = [a[0]]
g = a[0]

while m[g-1] == 0:
    l.append(a[g-1])
    m[g-1] = 1
    g = a[g-1]
 #   print(l)
 #   print(m)
 #   print(g)

loap_before = 0
loap_l = []
for i in range(len(l)):
    if l[-1] == l[i]:
        loap_before = i+1
        loap_l = l[i+1:]
        break
loap = len(l) - loap_before
if loap == 0:
    loap_l = l
#print(loap_before,loap_l,loap)

k -= loap_before
if loap != 0:    
    k = k%loap
#print(k)
if k == 0:
    print(loap_l[-1])
else:    
    print(loap_l[k-1])

Submission status: Runtime Error

Solution code:
#import sys
MOD = 10 ** 9 + 7
INFI = 10**10
#input = sys.stdin.readline
import math

import itertools
import heapq
#import bisect

import copy
from functools import lru_cache

def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

#    h,w,a,b = map(int, input().split())
#    c = [[0 for j in range(n)] for i in range(n)]

def ret(a):
    c=[None]*(len(a)-1)
    if len(a)==1:
        return a[0]
    elif len(a)==0:
        return 0
    for i in range(1,len(a)):
        c[i-1]=abs(a[i]-a[i-1])
    return ret(c)


def main():
    n,k=map(int,input().split())
    a =list(map(int,input().split()))
    town=[-1 for _ in range(n)]
    town[0]=0
    now=0
    for i in range(n):
        if town[a[now]-1]==-1:
            town[a[now]-1]=i+1
            now=a[now]-1
        else:
            sec=a[now]-1
            break
#        if i==n-1:
  #          sec=a[now]-1
    town2 = [-1 for _ in range(n)]
    town2[sec] = 0
    now = sec
    for i in range(n):
        if town2[a[now] - 1] == -1:
            town2[a[now] - 1] = i + 1
            now = a[now] - 1
        else:
            thi = a[now] - 1
            break
#    print(town)
#    print(town2)
    firstloop=max(town)+1
    secondloop=max(town2)+1
    ans=0
    if k<=firstloop:
        ans=town.index(k)+1
    else:
        k-=firstloop
        kai=k//secondloop
        k-=kai*secondloop
        ans=town2.index(k)+1
    print(ans)

if __name__ == "__main__":

    main()

Submission status: Runtime Error

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

index = 0
keiro = []
s_keiro = set()

for i in range(k):
  index = al[index] - 1
  if index in s_keiro:
    start = keiro.index(index)
    mod = i - start
    break
  s_keiro.add(index)
  keiro.append(index)

print(keiro[start + (k-start)%mod - 1]+1)

Submission status: Runtime Error

Solution code:

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

loop = [0]
loop_corr = []
while len(loop) < k:
    curr = loop[len(loop) - 1]
    if a[curr] not in loop:
        loop.append(a[curr])
        # print(loop)
    else:
        loop_corr = loop[loop.index(a[curr]):len(loop)]
        break

if len(loop) > k:
    print(loop[k]+1)
else:
    diff = k - len(loop) + 1
    mod = (diff % len(loop_corr)) -1
    print(loop_corr[mod]+1)

Submission status: Runtime Error

Solution code:
import sys
n, k = map(int, sys.stdin.readline().split())
li = list(map(int, sys.stdin.readline().split()))
li1 = [0]*n
li2 = [0,]
cnt = 0
t = 0
i = 1
while cnt < k:
  i = li[i-1]
  if li2.count(i-1) == 0:
    li2.append(i-1)
  else:
    li2.append(i-1)
    t = i-1
    break
  cnt += 1
a = li2.index(li2[-1])
b = a
a = len(li2) - a - 1
k -= b+1
k %= a
li2 = li2[b:]
print(li[li2[k]])

Submission status: Runtime Error

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

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

fumi = set([0])
start = None
end = None
aab = [0]
for i in range(1*10**5):
    next = aa[aab[-1]] - 1
    if next in fumi:
        if start is None:
            start = i
            fumi = set()
        else:
            end = i
            break
    aab.append(next)
    fumi.add(next)

random_first = len(aab) - 2*(end - start)
#print(aab, start, end, aab[start+1:end+1], aab[:random_first])

first = aab[:random_first]
one_cicle = aab[start+1:end+1]
if k <= len(first):
    print(first[k]+1)
else:
    k = k-len(first)
    print(one_cicle[k%len(one_cicle)]+1)

Submission status: Runtime Error

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

A_itta = [None] * N
# A_cycle = '1'

A_stayed = []
A_stayed.append('1')

i = 0
while True:
    # print('stay', i)

    # 訪問フラグ
    A_itta[i] = 1

    # 訪問リスト
    # A_cycle = A_cycle + str(A[i])
    A_stayed.append(str(A[i]))

    # 次の番号
    i = A[i] - 1

    # print('next', i)

    # 行ったことある
    if A_itta[i]:
        # print('loop at=', i)
        break

# 最初の町からループする場合
if i == 0:
    # cycle = A_cycle[0:-1]
    cycle = A_stayed[0:-1]
    ans = cycle[K % len(cycle)]

else:
    # cycle = A_cycle[i + 1:-1]
    cycle = A_stayed[i+1:-1]
    ans = cycle[(K - (i + 1)) % len(cycle)]

# print(cycle)
print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

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

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


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

ml,mr=mod
k=(k-ml)%(mr-ml)
if k==0:
    k+=(mr-ml)
k+=ml
# print(k)

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

Submission status: Runtime Error

Solution code:
def dfs(now):
    global m
    if now in l:
        m = now
        return None
    else:
        l.append(now)
        dfs(a[now - 1])
n, k = map(int, input().split())
a = list(map(int, input().split()))
m = float("inf")
l = []
cycle = float("inf")
ans = []
dfs(a[0])
for i in range(len(l)):
    if l[i] == m:
        ans = l[i:]
        cycle = len(ans)
if k % cycle == 0:
    print(ans[-1])
else:
    print(ans[(k - (len(l) - cycle)) % cycle - 1])

Submission status: Runtime Error

Solution code:
n,k =map(int,input().split())
a = list(map(int,input().split()))
l = 0    
for i in range(k) :
    m = a[l]
    l = m 
print(l+1)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
#それまでに登場した数字が入っていた場合にループ発生
i=0
pasta=[1]
while 0==0:
    if a[i] in pasta:
        roopy=pasta.index(a[i])
        roop=pasta[roopy:]
        break
    else:
        pasta.append(a[i])
        i=a[i]-1
if k>len(pasta):
    k-=len(pasta)
    k%=len(roop)
    print(roop[k])
else:
    print(pasta(k))

Submission status: Runtime Error

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

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

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

Submission status: Runtime Error

Solution code:
from sys import stdin
def main():
    N, K = [int(x) for x in stdin.readline().rstrip().split()]
    A = [int(x) for x in stdin.readline().rstrip().split()]
    X = 0
    C = 0
    Log = []
    while C <= K:
        X = A[X-1]
        C += 1
        if (X in Log) == True:
            break
        Log += [X]
        
        #print(Log)
        #print('C',C)
        #print('X',X)
        
    K = (K - C + 1)%(C - Log.index(X))
    #print(K)
    print(Log[Log.index(X)+K])
    
main()

Submission status: Runtime Error

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

visited = [0] * n
visited[0] = 1
visit_list = [0]
visit = 0
while True:
    new_visit = a[visit]
    if visited[new_visit] == 1:
        break
    visited[new_visit] = 1
    visit_list.append(new_visit)
    visit = new_visit

period_first_index = visit_list.index(a[visit_list[-1]])
period_list = visit_list[period_first_index:]
period = len(visit_list) - period_first_index

if k <= len(visit_list):
    print(visit_list[k]+1)
else:
    print(period_list[(k-period_first_index)%period]+1)

Submission status: Runtime Error

Solution code:
n,k=(int(i) for i in input().split())
r=[0 for i in range(n)]
l=[int(i) for i in input().split()]
wazap=[]
count=1
saver=None
temp=0
while r[temp]==0:
  r[temp]=count
  wazap.append(temp)
  temp=l[temp]-1
start=wazap[-1]
for i in range(len(wazap)):
  if wazap[i]==start-1:
    left=i
    break
loop=len(wazap)-left
if k<left:
  print(wazap[k]+1)
else:
  print(wazap[(k-left)%loop+left]+1)