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:
nk = input().split()
n , k = int(nk[0]), int(nk[1])
a = [int(i) for i in input().split()]

t = 1
tl = [1]
ts = {1}

flg = False
for i in range(len(a)):
    # flg = t > a[t-1]
    t  = a[t-1]
    # stl = sorted(tl)
    if t in ts:
        break
    else:
        tl.append(t)
        ts.add(t)

tl2 = tl[tl.index(t):len(tl)]
         
# print(tl)
# print(tl2)

ans = 0

if k <= len(tl):
    ans = tl[k]
else:
    k = k - len(tl)
    j = k % len(tl2)
    ans = tl2[j]

print(ans)

Submission status: Runtime Error

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

a_list = list(map(int, input().split()))
check_point = [0] * N
check_point[0] = 1

def warp(a_list, check_point, now_position = 1):
  next_position = a_list[now_position-1]
  check_point[next_position-1] += 1
  if 3 in check_point:
    return check_point
  warp(a_list, check_point, next_position)

def warp2(a_list, counter = 1, now_position = 1):
  next_position = a_list[now_position-1]
  counter += 1
  if counter == act_:
    return next_position
  warp(a_list, counter, next_position)
  
warp(a_list, check_point)

before_loop = check_point.count(1)
len_loop = check_point.count(2) + check_point.count(3)
act_ = before_loop + (K - before_loop) % len_loop
ans = warp2(a_list)

print(a_list[ans-1])

Submission status: Runtime Error

Solution code:
def main():

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

    zzz=[]
    oioi=0
    flg=False

    for i in range(1,n+1):
        oioi = a[oioi]-1
        zzz.append(oioi)
        if oioi == 0:
            break
        if oioi in zzz:
            flg=True
            ppp=zzz.index(oioi)
            qqq=len(zzz)
            li=zzz
            del zzz[0:ppp+1]
            break


    
    if k>=qqq and flg:
        print(zzz[(k+ppp)%len(zzz)-1]+1)
    elif k<=qqq and flg:
        print(li[k-1]+1)
    else:    
        print(zzz[k%len(zzz)-1]+1)

    

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

gone = []


def dfs(index):
    if index in gone:
        return

    gone.append(index)
    dfs(Alist[index-1])


dfs(1)

for g in range(0, len(gone)-1):
    if Alist[gone[g]-1] == gone[-1]:
        gone = gone[g-1:]
        index = g-1


ansi = K % len(gone)

print(gone[ansi-index])

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
teleport = dict()
for i, a in enumerate(A):
    teleport[i+1] = a

state = 1
connect = [1]
looplen= 10**18
for n in range(N):
    state = teleport[state] 
    print(state)
    print(connect)
    if state in connect:
        loop_init = connect.index(state)
        looplen = n-connect.index(state)+1
        break
    else:
        connect.append(state)
        
index = (K-loop_init)%looplen
end = connect[loop_init+index]
print(end)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
N, K = map(int, input().split())
A = np.array(list(map(int, input().split())))
A = np.insert(A, 0, 0)

flg = [False for _ in range(N + 1)]
town = []
i = 1
cnt = 0
while flg[i] == False or cnt > N:
    town.append(i)
    flg[i] = True
    i = A[i]
    cnt += 1

if len(town) >= K:
    print(town[K])
else:
    s = i
    to_s = town.index(s)
    loop = len(town) - to_s
    print(town[(K - to_s) % loop + to_s])

Submission status: Runtime Error

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

if K >= N:
    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
    K -= n0
    r = K % num
    n = n0
else:
    n = 0
    
for _ in range(r):
    n = A[n] - 1

print(n0+n+1)

Submission status: Runtime Error

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

A = deque(map(int, input().split()))
li = []
li2 = [0]*n
li.append(1)

next = 0
t=0
rep = False

for i in range(n):
    li.append(A[next])
    li2[next] = 1
    next = A[next]-1

    if li2[next] == 1:
        t = li.index(A[next])
        rep = True
        break


if rep == True and t != 0:
    tmp = (k%len(li[t:])) - len(li[0:t])
    g=li[t:]
    print(g[tmp])
else:
    print(li[k-1])

Submission status: Runtime Error

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

X = [-1]*N

# print(X)
ikisaki = Line[0]
X[0] = 0

# print(ikisaki)

for i in range(N+1):
    if X[ikisaki-1] == -1:
        X[ikisaki-1] = i + 1
        ikisaki = Line[ikisaki-1]
    else:
        warukazu = i+1 - X[ikisaki-1]
        break
    print(X)

print(warukazu)
Z = K%warukazu
print(Z)

print(X.index(Z)+1)

Submission status: Runtime Error

Solution code:
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections


n,k = map(int,input().split())
a = list(map(int,input().split()))
for i in range(len(a)):
    a[i] -= 1
pre = 0
d = []
for i in range(2*n+10):
    d.append(pre)
    pre = a[pre]
cnt = [0]*(n)
s = ""
for i in range(len(d)):
    cnt[d[i]]+=1
    if cnt[d[i]]>=3 and cnt[d[i]]<4:
        s += str(d[i])
ff = int(s[0])
for i in range(len(d)):
    if ff == d[i]:
        check = i
        break
if check == 0:
    k %= len(s)
    print(a[k]+1)
else:
    k-= check
    k%=len(s)
    print(int(s[k])+1)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
i=0
pasta=[1]
memo=[0]*n
while True:
    if memo[a[i]-1]==1:
        roopy=pasta.index(a[i])
        roop=pasta[roopy:]
        break
    else:
        memo[a[i]-1]+=1
        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:
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=0
    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: Runtime Error

Solution code:
n,k=map(int,input().split(" "))
tele=list(map(int,input().split(" ")))
c=[]##循环路线
c1=[]##装多的
special=[]##原地不动
times=0
city=1
rem=0
if tele[0]==1:
    print(1)
else:
    ##找原地不动
    for j in range(n):
        if j+1==tele[j] :
            special.append(j+1)
    ##找循环
    for i in range(n):
        times+=1
        city=tele[city-1]
        if city in special:
            print(city)
            break
        if city in c:
            break
        c.append(city)
    ##去掉不是循环的城市并转到c1
    for cit in c:
        if cit != city:
            rem+=1
            c.remove(cit)
            c1.append(cit)
        else:
            break
    ##打印
    if k>rem:
        k-=rem
        k=k%len(c)
        print(c[k-1])
    elif k ==0:
        print(1)
    elif k <=rem:
        print(c1[k-1])

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
B = []
B.append(A[0])
b = 1
ans = 1
while ans:
  a = b
  b = A[a-1]
  B.append(b)
  if len(B) == len(A):
    ans = 0

print(B[k])

Submission status: Runtime Error

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

l = [1]
s = {1}

while True:
    next = list_A[l[-1] - 1]

    if not next in s:
        l.append(next)
        s.add(next)

    else:
        start = l.index(next)
        roop = len(l) - start
        break

if len(l) == 1:
    print(1)
    exit()

elif len(l) >= K:
    print(l[K])
    exit()

else:
    roop_remainder = (K + 1 - start) % roop
    if roop_remainder == 0:
        print(l[-1])
    else:
        print(l[start + roop_remainder -1])

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
teleport = dict()
for i, a in enumerate(A):
    teleport[i+1] = a

state = 1
connect = [1]
looplen= 10**18
for n in range(N):
    state = teleport[state] 
    #print(state)
    #print(connect)
    if state in connect:
        loop_init = connect.index(state)
        looplen = n-connect.index(state)+1
        break
    else:
        connect.append(state)
        
index = (k-loop_init)%looplen
end = connect[loop_init+index]
print(end)

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

def main():
    ans = 0
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    b = []
    next = a[0]
    b.append(next)
    s = e = 0
    for i in range(n-1):
        next = a[next-1]
        if next in b:
            s = b.index(next)
            e = i
            break
        b.append(next)
    ans = k%n
    print(b[ans])
if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

town_check = {0}
town_order = [0]
town = 0
check1 = True
while check1:
    next_town = A[town] - 1
    if next_town not in town_check:
        town = next_town 
        town_check.add(town)
        town_order.append(town)
    else:
        loop = (next_town, town)
        check1 = False

if K-1 <= len(town_order):
    print(town_order[K]+1)
else:
    a = town_order.index(loop[0])
    b = len(town_order) - 1
    c = b - a + 1
    print(town_order[a+(K-a)%(c)]+1)

Submission status: Runtime Error

Solution code:
def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    check = [0] * N
    cnt = 0
    now_town = 1
    check[now_town - 1] = 1
    for i in range(K):
        cnt += 1
        now_town = A[now_town - 1]
        check[now_town - 1] += 1
        if max(check) == 2:
            break
    nokori = K - cnt
    cnt = 0
    check = [0] * N
    check[now_town - 1] = 1
    for i in range(nokori):
        cnt += 1
        now_town = A[now_town - 1]
        check[now_town - 1] += 1
        if max(check) == 2:
            break
    nokori = nokori % cnt
    for i in range(nokori):
        now_town = A[now_town - 1]
        check[now_town - 1] = 1
        print(now_town)
    print(now_town)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import os

def file_input():
    f = open('ABC167/input.txt', 'r')
    sys.stdin = f

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

    d=1
    # for i in range(K):
    #     # print(d)
    #     d=A[d-1]
    # li=[1]
    li=[False]*N
    li[0]=True

    while True:
        d=A[d-1]
        if li[d-1]:
            break
        # li.append(d)
        li[d-1]=True

    d_p=A.index(d)
    # print(d_p)
    roop=d-1-d_p
    # print(K-d_p)
    # print(len(li))
    # if len(li)>K:
    #     # print(K-1)
    #     print(li[K-1])
    # else:
    # print((K-d_p)%roop)
    print(A[(K-d_p)%roop+d_p])

    # print(d)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

B = [A[0]]

for _ in range(1, N + 10):
    b = A[B[-1] - 1]
    if b in B:
        B += [b]
        break
    else:
        B += [b]
        continue

if len(B) >= K:
    print(B[K])
else:
    ind = [i for i, x in enumerate(B) if x == b]

    K = K - ind[0]
    mod = K % (ind[1] - ind[0])

    print(B[ind[0] + mod - 1])

Submission status: Runtime Error

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

lst = [1]
visit_now = 1

visit_list = [0] * n
visit_list[0] = 1
while True:
    visit_now = a[visit_now - 1]
    if visit_list[visit_now - 1] == 1:
        break
    lst.append(visit_now)


start = lst.index(visit_now)
loop_num = n - start - 1
lst = lst[start:]

k -= start
k %= loop_num

print(lst[k])
# print(lst, loop_num, loop_list, k)

Submission status: Runtime Error

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

rireki = [0] * (n+10)
curr_c = 1
rireki[1] = 0

no_loop_count = k
loop_cnt = 0

mugen = False
for i in range(n):
    next_c = a_list[curr_c-1]
    # print(i, curr_c, next_c)
    if next_c == curr_c:
        mugen = True
    if next_c == 1:
        no_loop_count = 0
        loop_cnt = i + 1
        break
    elif rireki[next_c] == 0:
        rireki[next_c] = i+1
    else:
        # print(next_c)
        no_loop_count = rireki[next_c] -1
        loop_cnt = i - no_loop_count
        break
    curr_c = next_c

if loop_cnt ==0:
    loop_cnt = 1



if not mugen:
    if k <= no_loop_count or loop_cnt == 0:
        ans = rireki.index(k)
    else:
        # print('k',k)
        # print('no', no_loop_count)
        # print('lo', loop_cnt)
        ind = (k-1-no_loop_count)%loop_cnt +1
        rireki_fix = [i-no_loop_count for i in rireki]
        # print(ind, 'ind')
        ans = rireki_fix.index(ind)
        # print(rireki_fix)
        print(ans)

Submission status: Runtime Error

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

A = deque(map(int, input().split()))
li = []
li2 = [0]*n
li.append(1)

next = 0
t=0
rep = False

for i in range(n):
    li.append(A[next])
    li2[next] = 1
    next = A[next]-1

    if li2[next] == 1:
        t = li.index(A[next])
        rep = True
        break


if rep == True:
    tmp = (k%len(li[t:])) - len(li[0:t])
    g=li[t:]
    print(g[tmp])
else:
    print(li[k-1])

Submission status: Runtime Error

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

route = [-1] * N
route[0] = 0
P = 1
for i in range(1,K+1):
  P = A[P-1] 
  if route[P-1] == -1:
    route[P-1] = i
  
  else:
    ilast = i
    loop = i-P

    break
    

ans = (ilast - loop )+ (K-ilast+loop)%loop
P = A[route.index(ans)]


print(P)

Submission status: Runtime Error

Solution code:
N,K=map(int, input().split())
A=list(map(int, input().split()))
returnnum = 0
nowplace = 1
placedic = {0:1}
while True:
    nowplace = A[nowplace-1]
    returnnum += 1
    if nowplace in placedic.values():
        leftnum = K - placedic[nowplace]
        loopnum = returnnum - placedic[nowplace]
        print(placedic[placedic[nowplace]+leftnum%loopnum])
        break
    placedic[returnnum] = nowplace
    if returnnum == K:
        print(nowplace)
        break

Submission status: Runtime Error

Solution code:
import math
import queue
from collections import defaultdict
 
def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()
def factorization(n):
	res = []
	if n%2==0:
		res.append(2)
	for i in range(3,math.floor(n//2)+1,2):
		if n%i==0:
			c = 0
			for j in res:
				if i%j==0:
					c=1
			if c==0:
				res.append(i)
	return res
def fact2(n):
	p = factorization(n)
	res = []
	for i in p:
		c=0
		z=n
		while 1:
			if z%i==0:
				c+=1
				z/=i
			else:
				break
		res.append([i,c])
	return res
def fact(n):#階乗
	ans = 1
	m=n
	for _i in range(n-1):
		ans*=m
		m-=1
	return ans
def comb(n,r):#コンビネーション
	if n<r:
		return 0
	l = min(r,n-r)
	m=n
	u=1
	for _i in range(l):
		u*=m
		m-=1
	return u//fact(l)
def printQueue(q):
	r=qb
	ans=[0]*r.qsize()
	for i in range(r.qsize()-1,-1,-1):
		ans[i] = r.get()
	print(ans)
def dq():
	return queue.deque()
class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1]*n

	def find(self, x): # root
		if self.parents[x]<0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self,x,y):
		x = self.find(x)
		y = self.find(y)

		if x==y:
			return

		if self.parents[x]>self.parents[y]:
			x,y = y,x

		self.parents[x]+=self.parents[y]
		self.parents[y]=x

	def size(self,x):
		return -1*self.parents[self.find(x)]

	def same(self,x,y):
		return self.find(x)==self.find(y)

	def members(self,x): # much time
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i)==root]

	def roots(self):
		return [i for i,x in enumerate(self.parents) if x<0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()} # 1~n

n,k = readInts()
a = readInts()
ex = [0]*n
ex[0] = 0
ex_r = []
f = 1
l = 1
count = 0
if a[0]==1:
	print(1)
	exit()
while 1:
	l = a[l-1]
	ex_r.append(l)
	if ex[l-1]==1:
		break
	ex[l-1]=1

first = ex_r.index(ex_r[-1])
#print(ex_r)
p2 = ex_r[:-1]
#print(p2)
repeat = len(p2)-first
#print(first,repeat)

if k<=len(p2):
	print(ex_r[k-1])
else:
	y = (k-first)%repeat+repeat
	print(ex_r[first+y-1])

Submission status: Runtime Error

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

now=0
done=[]
for i in range(k):
  now=a[now]-1
  if now in done:
    now=done[k%(i+1)]
    break
  else:
    done.append(now)

now+=1
print(now)

Submission status: Runtime Error

Solution code:

import sys
input = sys.stdin.readline

def main():
    n, k = map(int, input().split())
    a = [0]
    ta = list(map(int, input().split()))
    a += ta
    kaiten = [0] * (n + 1)
    count = 0
    koko = 1
    kaitenkikan = 0
    while k > 0:
        koko = a[koko]
        count += 1
        k -= 1
        if kaiten[koko] > 0:
            kaitenkikan = abs(count - kaiten[koko])
            break
        else:
            kaiten[koko] = count
    k_remain = k % kaitenkikan
    if k_remain < 0:
        k_remain += kaitenkikan

    while k_remain > 0:
        koko = a[koko]
        k_remain -= 1

    print(koko)

if __name__ == '__main__':
    main()

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

cnt = [0]*(10**5)
cnt2 = [0]*(10**5)#何回目に出てきたか
t = []
nxt = 0
loop = 0

for i in range(10**5):
    cnt[nxt] += 1
    if cnt[nxt] >= 2:
        # print("i: " + str(i))
        # print("nxt: " + str(nxt))
        loop = i - cnt2[nxt]
        modC = max(0, cnt2[nxt])
        break
    cnt2[nxt] = i
    t.append(nxt)
    nxt = a[nxt]

modK = (k-modC)%loop
# print("-------")
# print(t)
# print("modC: " + str(modC))
# print("modK: " + str(modK))
# print("loop: " + str(loop))
# print(modK)
# print(loop)
# print("-------")

print(t[modC + modK] + 1)

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools

def main():
  n,k = map(int, input().split())
  a = list(map(int,sys.stdin.readline().split()))

  print(a)

  now = 0
  times = 0
  visit =[[0],[0]]

  for _ in range(k):
    times += 1
    now = a[now] - 1
    if now in visit[0]:
      roop = times - visit[1][visit[0].index(now)] #何個の町でループしてるかをroopに代入
      roop_start = visit[1][visit[0].index(now)] #ループが始めった待ちの最初に訪れた時に何回ループしていたかをroop_startに代入
      break
    else:
      visit[0].append(now)
      visit[1].append(times)

  k = (k - roop_start) % roop

  now = 0
  for _ in range(roop_start):
    now = a[now] - 1

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

  print(now+1)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

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

s = 0
m =[]

for i in range(K):
	s = l[s] - 1
    m.append(s)
    if len(m) != len(set(m)):
      ## int = m.index(s) - len(m)
      x = K - m.index(s) // int
      y = K - m.index(s) - x*int
      result = m[y]
      break
    

print(result + 1)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**5)
n,k = map(int,input().split())
l = list(map(int,input().split()))
def trans(n):
    if n == 1:
        return l[0]
    else:
        return l[trans(n-1)-1]
print(trans(k))

Submission status: Runtime Error

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

visited = [0]
x=1
for i in range(n):
  x = a[i]
  if x in visited:
    for j in range(i):
      if visited[j] == x:
        first = j
        break
    T = i - j
  else:
    visited.append(a[i])
mod = (k-first) % T
print(a[first+mod])

Submission status: Runtime Error

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

li = [0]
li.extend(list(map(int, input().split())))
tuita = [0]*(n+1)
cnt = 0
town = 1

def search(town, times):
  if times == 0:
    return town
  return search(li[town], times - 1)

lastTown = 1
while True:
  town = li[town]
  cnt += 1
  if tuita[town] == 0:
    tuita[town] = cnt
  else:
    if k < tuita[town]:
      lastTown = 1
      times = k
    elif k == tuita[town]:
      print(town)
      lastTown = 1
      times = 0
    else:
      lastTown = town
      times = (k - tuita[town]) % (cnt - tuita[town])
    break

ans = search(lastTown, times)
print(ans)

Submission status: Runtime Error

Solution code:
from sys import stdin
import sys

N, K = [int(x) for x in stdin.readline().rstrip().split()]
A = list(map(int, input().split()))
B = [i for i in range(1, N+1)]
d = dict(zip(B, A))
t = [0 for i in range(N)]
d1 = dict(zip(B, t))
temp = 1
cnt = 0
ans = []
for i in range(K):
    d1[d[temp]] = d1.get(d[temp], 0)+1
    if d1.get(d[temp], 0) == 2:
        cnt += 1
        ans.append(d[temp])
        # print(i, d[temp])
    if d1.get(d[temp], 0) == 3:
        break
    temp = d[temp]
    if i == K-1:
        print(temp)
        sys.exit()
cnt1 = 0
x = 1/cnt1
for i, v in enumerate(d1):
    if v == 1:
        cnt1 += 1
# print(cnt, cnt1, d1, temp, ans)
k = K-1-cnt1
print(ans[k % cnt])

Submission status: Runtime Error

Solution code:
import sys

n,k = (int(i) for i in input().split())

a = [int(i)-1 for i in input().split()]

hantei = [True]*(n+1)
otozure = [None]*(n+1)
mokuteki = a[0]
moto = k
kazoe = 0
otozure[0] = 0
while k>0:
        
    if hantei[mokuteki] == False: #二週目突入
       # print("break\nmokuteki= {}\nk = {}".format(mokuteki,k))
        otozure[kazoe+1] = mokuteki
        saigo = otozure
        break

    else:
        hantei[mokuteki]= False
        otozure[kazoe+1] = mokuteki#今いるところを記憶
       # print(otozure[kazoe])
        mokuteki = a[mokuteki]#次に行くところ
        kazoe+=1
    k-=1
else:
    print(otozure[kazoe-1])
    sys.exit()
i = 0
while True:
    if otozure[kazoe+1] == otozure[kazoe-i]:
        break
    i+=1


nokori = k%(i+1)
#print(nokori)
i=0
while otozure[i] != mokuteki:
    i+=1

print(otozure[i-1+nokori]+1)

Submission status: Runtime Error

Solution code:

def main():
    n,k = map(int,input().split())
    dests =[0 for _ in range(n)]
    telepos = list(map(int,input().split()))
    for i,t in enumerate(telepos):
        dests[i] = t-1
    print(dfs(dests,k))




def solve(dests,k,here = 0):
    here = 0
    telepo_times = 0
    cycle_start = -1
    cycle_end = -1
    cycle_length = -1
    visited = []
    ids = dict()


    #循環検出！同じ町にいつ戻ってくるのか
    while telepo_times < k:
        #print("現在地は",here)
        if here in visited:
            cycle_start = ids[here]
            #print(cycle_start,"でループが始まった")
            cycle_end = telepo_times - 1
            #print(cycle_end,"でループが終わった")
            cycle_length = cycle_end - cycle_start + 1
            #print("サイクルの長さは",cycle_length,"だ")
            break
        ids[here] = telepo_times

        visited.append(here)
        telepo_times += 1
        here = dests[here]
    if cycle_length == -1:
        return here + 1

    cycle_index = (k-cycle_start) % cycle_length
    return visited[cycle_start + cycle_index] + 1




    #telepo_times = 0
    #while telepo_times < (k - cycle_start)%cycle_length:
    #    telepo_times += 1
    #    here = dests[here]







if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
a,b=map(int,input().split())
city=list(map(int,input().split()))
if a<40000:
    a=40000
ne=[0]*a
ne[0]=1
for i in range(a-1):
    ne[i+1]=city[ne[i]-1]
rpp=[]
nrp=[]
for i in ne[1:20000]:
    if i in ne[20001:40000]:
        rpp.append(i)
for i in ne[0:20000]:
    if i not in ne[20001:40000]:
        nrp.append(i)
if len(nrp)>=b-1:
    print(ne[b])
else:
    print(rpp[((b-len(nrp)-1)%len(rpp))])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(8388608)
# 町: N個
# 移動回数: K
N, K = map(int, input().split())

# 次の町番号
A = list(map(int, input().split()))

flg = [False]* len(A)   # 既にきたことある町

townLoop = []
def warp(k, nowTown):
    # 移動回数が残っている
    if K+1 != k:
        #print(k, nowTown, A[nowTown-1])
        
        # まだ来たことのない町
        if flg[nowTown-1] == False:
            flg[nowTown-1] = True
            townLoop.append(A[nowTown-1])
            warp(k+1, A[nowTown-1] )
        else:
            return 
    else:
        return 
        #print(A[nowTown-1])

warp(0, A[0])


#print(townLoop)
if townLoop[0] == townLoop[len(townLoop)-1]:
    townLoop.pop(len(townLoop)-1)
#//print((K-1) // len(townLoop))
tmp = K-1
while(True):
    tmp = tmp // len(townLoop)
    if tmp < len(townLoop):
        #print(tmp)
        break
print(townLoop[tmp-1])

Submission status: Runtime Error

Solution code:
NK = [int(x) for x in input().split()]
N=NK[0]
K=NK[1]
A = [int(x) for x in input().split()]
    
j=1 
ii=0
C=[]
for i in range(N+1):#i:1~N
  j=A[j-1]
  if j in C:
    ii=C.index(j)+1
    T=j-ii+1
    break
  C.append(j)
if K<ii:
  print(C[K-1])
else:
  print(C[(K-ii)%T+ii-1])

"""
6 727202214173249351
6 5 2 5 3 2
2
"""

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
tmp = list(map(int, input().split()))
A = [1]
A.extend(tmp)

# 循環する場所を探す(最大N回)
used = [1, 1]
used.extend([0] * (N-1)) # すでに通った町は1にする
route = [1]
while used[A[route[-1]]] == 0:
    used[A[route[-1]]] = 1
    route.append(A[route[-1]])

if A.index(A[route[-1]]) == 0:
    print(route[K%(len(route))])
else:
    x = A.index(A[route[-1]]) - 1
    y = len(route) - x
    if y == 0:
        print(route[x])
    else:
        print(route[x + (K-x)%y])

Submission status: Runtime Error

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

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

city = 1
route = []
cnt = [0] * n
cnt[0] += 1
route.append(0)


while True:
    city = roads[city-1] 
    cnt[city-1] += 1
    if cnt[city-1] == 2:
        st = route.index(city)
        length = len(route) - st
        break
    route.append(city)

if k <= len(route):
    print(route[k])

elif length >= 1:
    amari = (k+1-st) % length
    if amari  == 0:
        print(route[-1])
    else:
        print(route[amari+st-1])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
count=0
lst=[]
now=1
for i in range(n):
    if now in lst:
        
        break
    lst.append(now)
    now=a[now-1]
ind=lst.index(now)

if k<=len(lst):
    print(lst[k])

else:
    newlst=lst[ind:]
    num=len(lst)-len(newlst)
    newk=k-num
    num2=newk%len(newlst)
    print(newlst[num2])

Submission status: Runtime Error

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

zyun = [a[0]]
alr = [False]*n
alr[0] = True
crr = a[0]

key = True

while key:
    if not alr[crr - 1]:
        alr[crr - 1] = True
        crr = a[crr - 1]
        zyun.append(crr)
        continue
    else:
        index1 = crr
        key = False

p = zyun[index1]
# print(zyun, p, zyun.index(p))

if zyun.index(p) - 1 == 0:
    zyun1 = zyun
    zyun2 = zyun
else:
    zyun1 = zyun[:zyun.index(p)]
    zyun2 = zyun[zyun.index(p):]

# print(zyun1, zyun2)

if len(zyun1) >= k:
    print(zyun1[k])
else:
    ind = (k - len(zyun1)) % len(zyun2)
    if ind == 0:
        print(zyun2[-1])
    else:
        print(zyun2[ind - 1])

Submission status: Runtime Error

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

rireki = [0] * (n+10)
curr_c = 1
rireki[1] = 0

no_loop_count = k
loop_cnt = 1

mugen = False
for i in range(n):
    next_c = a_list[curr_c-1]
    # print(i, curr_c, next_c)
    # if next_c == curr_c:
    #     mugen = True
    if next_c == 1:
        no_loop_count = 0
        loop_cnt = i + 1
        break
    elif rireki[next_c] == 0:
        rireki[next_c] = i+1
    else:
        # print(next_c)
        no_loop_count = rireki[next_c] -1
        loop_cnt = i - no_loop_count
        break
    curr_c = next_c

if loop_cnt ==0:
    loop_cnt = 1

# if not mugen:
if k <= no_loop_count:
    ans = rireki.index(k)
else:
    # print('k',k)
    # print('no', no_loop_count)
    # print('lo', loop_cnt)
    ind = (k-1-no_loop_count)%loop_cnt +1
    rireki_fix = [i-no_loop_count for i in rireki]
    # print(ind, 'ind')
    ans = rireki_fix.index(ind)
    # print(rireki_fix)
    print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
A_list =  list(map(int, input().split()))
A_list
toutatul = [0]*N
next_jump = 0
before =-1
toutatul[0] =1
asibumi =False
asibumitown =0
roop_start = 0
roop_end =0
roop_count =0
for x in range(len(A_list)):
    A_list[x] = A_list[x]-1
for x in range(N):
    before = next_jump
    next_jump = A_list[next_jump]
    if toutatul[next_jump] ==1:
        roop_start =next_jump
        roop_end =before
        roop_count =x+1
        break
    toutatul[next_jump] =1
    if next_jump == before:
        asibumi =True
        asibumitown = next_jump
        break

next_jump = 0
before =0

if asibumi:
    if N<K:
        ans =asibumitown
    else :
        for x in range(K):
            before = next_jump
            next_jump = A_list[next_jump]

        ans = next_jump
else :
    if N<K:
        next_jump = roop_start
        roop_long = 0
        for x in range(roop_count):
            if next_jump ==roop_end:
                break
            next_jump = A_list[next_jump]
            roop_long +=1
        move = (K-roop_count)%roop_long+1
        next_jump = roop_start+1
        for x in range(move):
            print(next_jump)
            before = next_jump
            next_jump = A_list[next_jump]
            
        ans = next_jump 
    else :
        for x in range(K):
            before = next_jump
            next_jump = A_list[next_jump]

        ans = next_jump
print(ans+1)