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:
N, K = map(int, input().split())
A = list(map(int, input().split()))

a = 0
n = A[0]
lis = [1,n]

def dupli(seq):
    return len(seq) != len(set(seq))

while a < K - 1:
    a = a + 1
    n = A[n-1]
    if dupli(lis) == True:
        break
    lis.append(n)

num = (K-lis.index(A[n-1])-1) %(lis.index(A[n-1]) - lis.index(A[n])+1)

t = (lis.index(A[n-1]) - lis.index(A[n])+1)

print(A[n-t+num])

Submission status: Runtime Error

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

a = 0
n = A[0]
lis = [1,n]

return len(seq) != len(set(seq))

while a < K - 1:
    a = a + 1
    n = A[n-1]
    #print(lis)
    if dupli(lis) == True:
        break
    lis.append(n)

#print(lis[K % len(lis)])

num = (K-lis.index(A[n-1])-1) %(lis.index(A[n-1]) - lis.index(A[n])+1)

t = (lis.index(A[n-1]) - lis.index(A[n])+1)

print(A[n-t+num])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[1]
cnt=0
loop=0
index=0
while(len(town) <= k):
    town.append(a[town[-1]-1])
    cnt+=1
    index=len(town)-1
    if cnt != index:
        loop = cnt - index
        town.pop(-1)
        break

if k<index:
    print(town[k])
else:
    k-=index
    k%=loop
    print(town[index+k])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[1]
cnt=0
loop=0
index=0
while(len(town) <= k):
    town.append(a[town[-1]-1])
    cnt+=1
    index=town.index(town[-1])
    if cnt != index:
        loop = cnt - index
        town.pop(-1)
        break

if k<index:
    print(town[k])
else:
    k-=index
    k%=loop
    print(town[index+k])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[1]
cnt=0
loop=0
index=0
while(len(town) <= k):
    town.append(a[town[-1]-1])
    cnt+=1
    index=town.index(town[-1])
    if cnt != index:
        loop = cnt - index
        town.pop(-1)
        break

if k<index:
    print(town[k])
else:
    for i in range(0,index):
        town.pop(0)
    print(town[(k-index)%loop])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[1]
cnt=0
loop=0
index=0
while(len(town) <= k):
    town.append(a[town[-1]-1])
    cnt+=1
    index=town.index(town[-1])
    if cnt != index:
        loop = cnt - index
        town.pop(-1)
        break
town2=[]
if k<index:
    print(town[k])
else:
    for i in range(index,len(town)):
        town2.append(town[i])
    print(town2[(k-index)%loop])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
town=[1]
cnt=0
loop=0
index=0
while(len(town) <= 10):
    town.append(a[town[-1]-1])
    cnt+=1
    index=town.index(town[-1])
    if cnt != index:
        loop = cnt - index
        town.pop(-1)
        break
town2=[]
if k<index:
    print(town[k])
else:
    for i in range(index,len(town)):
        town2.append(town[i])
    print(town2[(k-index)%loop])

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=[int(i) for i in input().split()]
k=[1]
a=1
for i in range(N):
    a=A[a-1]
    k.append(a)
    if i+2!=len(set(k)):
        del k[-1]
        Y=k[0:k.index(a)]
        Z=k[k.index(a):]
        break
    else:
        continue
if K<=len(Y):
    print(Z[K])
else:
    S=(K-len(Y))%(len(Z)) 
    print(Z[S])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(lambda x: int(x) - 1, input().split()))
visited = [-1 for _ in range(n)]
visited[0] = 0
l = [0]
for i in range(k):
    nex = a[l[i]]
    if visited[nex] != -1:
        res = visited[nex]
        cyc = i + 1 - visited[nex]
        break
    else:
        l += [nex]
        visited[nex] = i + 1
print(l[res + (k - res) % cyc] + 1 if k > res else l[k] + 1)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(lambda x: int(x) - 1, input().split()))
visited = [-1 for _ in range(n)]
visited[0] = 0
l = [0]
for i in range(k):
    nex = a[l[i]]
    if visited[nex] != -1:
        res = visited[nex]
        cyc = i + 1 - visited[nex]
        break
    else:
        l += [nex]s
        visited[nex] = i + 1
print(l[res + (k - res) % cyc] + 1 if k > res else l[k] + 1)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(lambda x: int(x) - 1, input().split()))
visited = [-1 for _ in range(n)]
visited[0] = 0
l = [0]
for i in range(k):
    nex = a[l[i]]
    if visited[nex] != -1:
        res = visited[nex]
        cyc = i + 1 - visited[nex]
        break
    else:
        l += [nex]s
        visited[nex] = i + 1
else:
    res = k + 1
print(l[res + (k - res) % cyc] + 1 if k > res else l[k] + 1)

Submission status: Runtime Error

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


boolean=[0]*n

#naive recursive calls
#we know that if at one point we land on a visited city
#A loop will be created


    

def jump(array,k,pointer,count,state):

    if k>0:
        boolean[pointer-1]+=1
        if boolean[pointer-1]==2:
            count+=1
        elif boolean[pointer-1]==3 and state is False:
            kloop=k%count
            state=True
            return jump(array,kloop,pointer,count,state)
            
        return jump(array,k-1,array[pointer-1],count,state)
    elif k==0:
        return pointer
    

print(jump(array,k,1,0,False))

Submission status: Runtime Error

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

A.insert(0,-1)
root = [1]
next = A[1]
rf = 0

for _ in range(K):
    if next not in root:
        root.append(next)
        next = A[next]
    else:
        rf = root.index(next)
        roop = root[rf:]
        break


print(root[(K - rf - 1) % len(roop)])

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
visited = []
search = set()
now = 1#最初の街にいる
next_town = A[now-1]
count = 1
while(count<=N):
    if next_town in search:#もし次の街が訪れたことがある場合
        break#ループするので抜け出す
    visited.append(now)#今いる街は訪れたこととなるので記録する
    search.add(now)
    next_town = A[now-1]#次に行く街を探す
    now = next_town#次の街に着いたこととして変数を代入
    count += 1

first_roop_city = A[visited[-1]-1]#最初にループした街
first_roop_city_index = visited.index(first_roop_city)#何回目のテレポートにループが始まったか
if K <= len(visited):
    print(visited[K])
else:
    visited = visited[first_roop_city_index:]
    L = len(visited)
    print(visited[(K-first_roop_city_index)%L])

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
visited = []
search = set()
now = 1#最初の街にいる
count = 0
next_town = A[now-1]
while(count<=N):
    if next_town in search:#もし次の街が訪れたことがある場合
        break#ループするので抜け出す
    visited.append(now)#今いる街は訪れたこととなるので記録する
    search.add(now)
    next_town = A[now-1]#次に行く街を探す
    now = next_town#次の街に着いたこととして変数を代入
    count += 1

first_roop_city = A[visited[-1]-1]#最初にループした街
first_roop_city_index = visited.index(first_roop_city)#何回目のテレポートにループが始まったか
if K <= len(visited):
    print(visited[K])
else:
    visited = visited[first_roop_city_index:]
    L = len(visited)
    print(visited[(K-first_roop_city_index)%L])

Submission status: Runtime Error

Solution code:
N,K = (int(i) for i in input().split()) 
A = [int(i) for i in input().split()] 
A_done = [0]*N
A_route = []
point = 1
end_point = 0
while A_done[point-1]==0:
  A_done[point-1] = 1
  A_route.append(point)
  point = A[point-1]
  if A_done[point-1]==1:
    end_point = point
cal = K%len(A_route)
roop = A_route.index(end_point)
f_len = len(A_route[:roop])
roop_len = len(A_route[roop:])
A_roop = A_route[roop:]
if K >= f_len + roop_len:
  cal = (K-f_len)%(len(A_roop))
  #print(cal)
  print(A_roop[cal])
else:
  print(A_route(K))

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest

sys.setrecursionlimit(10**5)
def search(n, step, rec, seq, k):
	if rec[n] != -1:
		c = step - rec[n]
		sim = (k - rec[n]) % c
		v = n
		for i in range(sim):
			v = seq[v-1]
		print(v)
		return
	rec[n] = step
	search(seq[n-1], step + 1, rec, seq, k)

def resolve():
	n, k = map(int, input().split())
	seq = list(map(int, input().split()))
	rec = [-1]*(n+1)
	search(1, 0, rec, seq, k)
resolve()

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest

sys.setrecursionlimit(10**5)
def search(n, step, rec, seq, k):
	if rec[n] != -1:
		c = step - rec[n]
		sim = (k - rec[n]) % c
		v = n
		for i in range(sim):
			v = seq[v] - 1
		print(v+1)
		return
	rec[n] = step
	search(seq[n] - 1, step + 1, rec, seq, k)

def resolve():
	n, k = map(int, input().split())
	seq = list(map(int, input().split()))
	rec = [-1]*n
	search(0, 0, rec, seq, k)
resolve()

Submission status: Runtime Error

Solution code:
def search(n, step, rec, seq, k):
	if rec[n] != -1:
		c = step - rec[n]
		sim = (k - rec[n]) % c
		v = n
		for i in range(sim):
			v = seq[v] - 1
		print(v+1)
		return
	rec[n] = step
	search(seq[n] - 1, step + 1, rec, seq, k)

def resolve():
	n, k = map(int, input().split())
	seq = list(map(int, input().split()))
	rec = [-1]*n
	search(0, 0, rec, seq, k)
resolve()

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(lambda x:int(x)-1,input().split()))
lst=[0]
now=0
memo=0
town=[0]*n
town[0]=1
b=0 
for i in range(k):
  now=a[now]
  if town[now]==1:
    memo=now 
    b=1
    break
  lst.append(now)
  town[now]=1
if b==1:
    i=lst.index(now)　
    l=len(lst)
    if memo!=0:
      lst=lst[i:]
      l-=len(lst)
      print(lst[(k-l)%len(lst)]+1)
    else:
         print(lst[k%l]+1)
else:
  print(now+1)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(lambda x:int(x)-1,input().split()))
lst=[0]
now=0
memo=0
town=[0]*n
town[0]=1
b=0 
for i in range(k):
  now=a[now]
  if town[now]==1:
    memo=now 
    b=1
    break
  lst.append(now)
  town[now]=1
if b==1:
  i=lst.index(now)　
  l=len(lst)
  if memo!=0:
    lst=lst[i:]
    l-=len(lst)
    print(lst[(k-l)%len(lst)]+1)
  else:
    print(lst[k%l]+1)
else:
  print(now)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(lambda x:int(x)-1,input().split()))
lst=[0]
now=0
memo=0
town=[0]*n
town[0]=1
b=0 #フラグ
for i in range(k):
  now=a[now]#今どこにいるか
  if town[now]==1:#きたことがあるなら1
    memo=now #どこからループが始まるか覚えておく
    b=1
    break
  lst.append(now)
  town[now]=1
if b==1:
  i=lst.index(now)　
  l=len(lst)
  if memo!=0:
    lst=lst[i:]
    l-=len(lst)
    print(lst[(k-l)%len(lst)]+1)
  else:
    print(lst[k%l]+1)
else:
  print(now)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(lambda x:int(x)-1,input().split()))
lst=[0]
now=0
memo=0
town=[0]*n
town[0]=1
b=0 #フラグ
for i in range(k):
  now=a[now]#今どこにいるか
  if town[now]==1:#きたことがあるなら1
    memo=now #どこからループが始まるか覚えておく
    b=1
    break
  lst.append(now)
  town[now]=1
if b==1:
  i=lst.index(now)　
  l=len(lst)
  if memo!=0:
    lst=lst[i:]
    l-=len(lst)
    print(lst[(k-l)%len(lst)]+1)

Submission status: Runtime Error

Solution code:
from collections import deque

N, M = map(int, input().split())
AB = [map(int, input().split()) for _ in range(M)]

links = [[] for _ in range(N + 1)]
for a, b in AB:
    links[a].append(b)
    links[b].append(a)

result = [-1] * (N + 1)
q = deque([1])
while q:
    i = q.popleft()
    for j in links[i]:
        if result[j] == -1:
            result[j] = i
            q.append(j)
print('Yes')
print('\n'.join(str(i) for i in result[2:]))

Submission status: Runtime Error

Solution code:
#import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
N,K = LI()
A = LI()

#方針
#ループ検知でmod演算に移行
hist = []
now = 0
chk = [-1] * N
while True:
	hist.append(now+1)
	if chk[now] != -1:
		# ループ検知
		break
	chk[now] = len(hist)-1
	now = A[now]-1
K-=chk[hist[len(hist)-1]-1]
cutlist = hist[hist[len(hist)-1]+1:]
K%=len(cutlist)
print(cutlist[K-1])
#print("histpos[town]:",chk)
#print("hist:",hist)

Submission status: Runtime Error

Solution code:
def check(pair,m,x):
  l = len(pair)
  sum = 0
  
  for i in range(1,m):
    p = 0
    for j in range(l):
      p += pair[j][i]
    
    if(p < x):
      return -1
    
  for e in pair:
    sum += e[0]
  return sum
      
n,m,x = (int(x) for x in input().split())
a = []
for i in range(n):
  a.append(tuple([int(x) for x in input().split()]))
  
min = -1
  
for i in range(2 ** n):
  pair = []
  for j in range(n):
    if((i >> j) & 1):
      pair.append(a[j])
      
  sum = check(pair,m,x)
  if sum != -1:
    if min == -1:
      min = sum
    elif min > sum:
      min = sum
    
print(min)

Submission status: Runtime Error

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

loc = 0
visited_bkt = [-1 for _ in range(2 * 10 ** 5 + 1)]
count = 0
loop_len = -1
while True:
    visited_bkt[loc + 1] = count
    loc = a[loc]
    if visited_bkt[loc + 1] > 0:
        loop_len = count - visited_bkt[loc + 1] + 1
        break
    count += 1
start_len = count - loop_len
# print(visited_bkt)
# print(start_len, loop_len)
# print(start_len + (k - start_len) % loop_len if k >= count else k)
print(visited_bkt.index(start_len + (k - start_len) % loop_len) if k >= count else visited_bkt.index(k))

Submission status: Runtime Error

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

array = input().split()
for i in range(len(array)):
    array[i] = int(array[i])

now = 1

history = set()
start_number = -1

for i in range(K):
    history.add(now)
    now = array[now - 1]
    if(now in history):
        start_number = now
        break

if not(start_number == -1):
    start_ind = history.index(start_number)
    length = len(history) - start_ind
    mod = (K - start_ind) % length
    now = history[start_ind + mod]

print(now)

Submission status: Runtime Error

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

array = input().split()
for i in range(len(array)):
    array[i] = int(array[i])

now = 1

history = set()
start_number = -1

for i in range(K):
    history.append(now)
    now = array[now - 1]
    if(now in history):
        start_number = now
        break

if not(start_number == -1):
    start_ind = history.index(start_number)
    length = len(history) - start_ind
    mod = (K - start_ind) % length
    now = history[start_ind + mod]

print(now)

Submission status: Runtime Error

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

B[1]=1
i=0

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

    if(B[A[C[i-1]-1]]==-1):

        B[A[C[i-1]-1]]=A[C[i-1]-1]
        C[i]=A[C[i-1]-1]




    else:
        bfirst=C.index(A[C[i-1]-1])
        blast=i

        roop=blast-bfirst

        ans=(K-bfirst)%roop

        print(C[bfirst+ans])
        while(1):
            print(f)
        exit()

Submission status: Runtime Error

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

current = machi[n - 1]
re = [current]

def hantei(i):
    flag = False
    for r in re:
        if r == i: flag = True
    return flag

for _ in range(k):
    if hantei(machi[current-1]): break
    re += [machi[current-1]]
    current = machi[current-1]
    print(re)

print(re[k%len(re)])

Submission status: Runtime Error

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

current = machi[n - 1]
re = [current]

def hantei(i):
    flag = False
    for r in re:
        if r == i: flag = True
    return flag

for _ in range(k):
    if hantei(machi[current-1]): break
    re += [machi[current-1]]
    current = machi[current-1]
    print(re)

print(re[(k%len(re)])

Submission status: Runtime Error

Solution code:
#N,K入力
N,K= map(int,input().split())
#街の番号入力
A = [int(i) for i in input().split()]

# 重複した要素があるかどうかを判定
def has_duplicates(seq):
    return len(seq) == len(set(seq))

#移動経路
warp = [1]
a = 1

#同じ街にたどり着くまでループ
while has_duplicates(warp):
    a = A [a - 1]
    warp.append(a)
    #同じ街にたどり着かなかった場合はこっち
    if len(warp) == K +1:
        print(warp[K])
        break

l = [i for i, x in enumerate(warp) if x == a]

# 何回ワープしたらループする街に戻ってくるか
width = l[1] - l[0]

#　ループのどこに行くか
d = (K - l[0]) % (l[1]-l[0])

#結果の出力
print(A[d + l[0]])

Submission status: Runtime Error

Solution code:
#N,K入力
N,K= map(int,input().split())
#街の番号入力
A = [int(i) for i in input().split()]

# 重複した要素があるかどうかを判定
def has_duplicates(seq):
    return len(seq) == len(set(seq))

#移動経路
warp = [1]
a = 1

#同じ街にたどり着くまでループ
while has_duplicates(warp):
    a = A [a - 1]
    warp.append(a)
    #同じ街にたどり着かなかった場合はこっち
    if len(warp) == K +1:
        print(warp[K])
        break

l = [i for i, x in enumerate(warp) if x == a]

# 何回ワープしたらループする街に戻ってくるか
width = l[1] - l[0]

#　ループのどこに行くか
d = (K - l[0]) % (l[1]-l[0])

#結果の出力
print(d + l[0])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))

rem=k
nxt=1
visit=[]
visit_set={}
for i in range(k):
    visit.append(nxt)
    visit_set.add(nxt)
    nxt=a[nxt-1]
    # この判定をやめる
    if nxt in visit_set:
        break
    rem-=1

if rem==0:
    print(nxt)
else:
#    print('-'*60)
#    print('nxt=', nxt)
#    print('rem=', rem)
#    print('visit=', visit)
    
    loops=visit[visit.index(nxt):]
    print(loops[(rem-1)%len(loops)])    
    
#    print('-'*60)
#    print('loops=', loops)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))

rem=k-1
nxt=1
visit=[]
for i in range(k):
    visit.append(nxt)
    nxt=a[nxt-1]
    if nxt in visit:
        break
    rem-=i

if rem==0:
    print(nxt)
else:
    loops=visit[visit.index(nxt):]
    print(loops[(rem-1)%len(loops)])

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
a=0
cnt=0
anlist=[]
while True:
  if A[A[a]-1]==1:
    break
  else:
    anlist.append(A[A[a]-1])
    a=A[a]-1
    cnt+=1
res=N%cnt
ans=anlist[res]
print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
a=0
cnt=0
anlist=[0]*K
while True:
  if A[A[a]-1]==1:
    break
  else:
    anlist[cnt]=A[A[a]-1]
    a=A[a]-1
    cnt+=1
res=N%cnt
ans=anlist[res]
print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys,pprint

av = {}
passed = set()

(N,K) = [int(x) for x in input().split(" ")]

arrivalary = input().split(" ")
i = 1
while len(arrivalary) > 0:
    a = int(arrivalary.pop(0))
    av[i] = a
    i += 1

i = 0
loopflg = 0
pos = 1
nextpos = 0
loopstartpos = 0
loopstartnum = 0
loopcount = 0
while i < K:
    passed.add(pos)
    nextpos = av[pos]
    # print(i,pos,nextpos,loopflg,loopstartpos,loopcount,file=sys.stderr)
    if loopflg == 0 and nextpos in passed:
        loopflg = 1
        loopstartpos = nextpos
        loopstartnum = i
    elif loopflg == 1 and nextpos == loopstartpos:
        left = (K-loopstartnum) % loopcount
        i = K-left
    elif loopflg == 1:
        loopcount += 1
    pos = nextpos
    i += 1

print(pos)

Submission status: Runtime Error

Solution code:
from collections import deque

N, K = map(int, input().split())
A = list(map(int, input().split()))
cnt = 0
visited = deque()
next = 1
while True:
  present = next
  cnt += 1
  visited.append(present)
  next = A[present-1]
  if next in visited:
    ind = visited.index(next)
    l = len(visited[ind:])
    break

rest = (K-cnt) % l
present = visited[ind + rest]
print(present)

Submission status: Runtime Error

Solution code:
visited = [0]
visited_flg = [0 for _ in range(N)]
visited_flg[0] = 1
now_city = 0

next_city = A[0]
# visited.append(A[0])

# if K <= N:
#     p = 0
#     for _ in range(K):
#         p = A[p]
#     print(p + 1)
#     exit()


while True:
    next_city = A[now_city] 
    if visited_flg[next_city]:
        break
    
    now_city = next_city
    visited.append(now_city)
    visited_flg[now_city] = 1
    

loop_start = next_city
loop_city =  visited[visited.index(loop_start):]
k =  (K- len(visited)) % len(loop_city)
print(loop_city[k]+1)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
pos = 0
visit = [0] * n
move = []
loop = []
while visit[pos] != 2:
    if visit[pos] == 0:
        move.append(pos)
    else:
        loop.append(pos)
    visit[pos] += 1
    pos = a[pos] - 1
if len(move[k]) > k:
    print(move[k]+1)
else:
    print(loop[(k-(len(move)-len(loop)))%len(loop)]+1)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
pos = 0
visit = [0] * n
move = []
loop = []
while visit[pos] != 2:
    if visit[pos] == 0:
        move.append(pos)
    else:
        loop.append(pos)
    visit[pos] += 1
    pos = A[pos] - 1
if len(move[k]) > k:
    print(move[k]+1)
else:
    print(loop[(k-(len(move)-len(loop)))%len(loop)]+1)

Submission status: Runtime Error

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

pos = 0
visited = [0]*N
move = []
loop = []

while visited[pos]!=2:
  if visited[pos] ==0:
    move.append(pos)
  else:
    loop.append(pos)
  visited[pos] += 1
  pos = A[pos]-1

if len(move)>k:
  print(move[k]+1)
else:
  print(roop[(K-(len(move)-len(loop)))%len(loop)]+1)

Submission status: Runtime Error

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

dupli = set()
# dupli.add(1)

# index = A.index(1) if 1 in A else index = A[0]
if 1 in A:
    index = A.index(1)
else:
    index = A[0]

loop = 1
for i in range(N):
    v = A[index - 1]
    l = len(dupli)
    dupli.add(A[index - 1])
    if l == len(dupli):
        loop = len(dupli)
        break
    index = v

mod = K % loop

if 1 in A:
    index = A.index(1)
else:
    index = A[0]

for i in range(mod - 1):
    ans = A[index - 1]
    index = A[index - 1]

print(ans)

Submission status: Runtime Error

Solution code:
import math

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

    state = 1
    chklist = [0] * (N + 1)
    chklist_flag = [False] * (N + 1)
    chkmod = 0

    chklist_flag[0] = True

    for i in range(1, K + 1):
        state = A[state - 1]
        if chklist_flag[state - 1]:
            chkmod = (K - chklist[state - 1]) % (i - chklist[state - 1]) 
            chkrem = chklist[state - 1]
            break
        chklist[state - 1] = i 
        chklist_flag[state - 1] = True
    
    state = 1

    for i in range(chkrem + chkmod):
        state = A[state - 1]
    
    print(state)

if __name__ == "__main__":
    solve()

Submission status: Runtime Error

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

done_list = [1]
cur_place = 1
flag = True
for i in range(K):
    if a_list[cur_place-1] not in done_list:
        cur_place = a_list[cur_place-1]
        done_list.append(cur_place)
    else:
        period = len(done_list) - done_list.index(a_list[cur_place-1])
        print(done_list[done_list.index(a_list[cur_place-1]) + (K - i) % period + 1])
        flag = False
        break

if flag:        
    print(cur_place)

Submission status: Runtime Error

Solution code:
import math

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

    state = 0
    chklist = [0] * N
    chklist_flag = [False] * N
    chkmod = 0

    chklist_flag[0] = True

    for i in range(1, K + 1):
        if chklist_flag[state - 1]:
            chkmod = (K - chklist[state - 1]) % (i - chklist[state - 1]) 
            break
        chklist[state - 1] = i 
        chklist_flag[state - 1] = True
        state = A[state]
        print(chklist_flag)

    for i in range(chklist[state - 1] + chkmod):
        chklist[state - 1] = i 
        state = A[state- 1]

    print(state)

if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
import logging
logging.basicConfig(level=logging.INFO)
info = logging.getLogger(__name__).info

N,K = [int(x) for x in input().split()]
An = [int(x) for x in input().split()]

dupAn = set(An)
dupAn.add(1)
dupAn = {x for x in dupAn if An.count(x) > 1}

Ai = An[0]
loopi = 0
loopdict = {}
info("dupAn: {}".format(dupAn))
while loopi <= K:
  loopi += 1
  if Ai in dupAn:
    if loopdict.get(str(Ai)):
      loopdict[str(Ai)].append(loopi)
      break
    else:
      loopdict[str(Ai)] = [loopi]
  Ai = An[Ai-1]

info("find loop index{}".format(loopdict[str(Ai)]))

def getA(An, K):
  print("getA {} {}".format(An,K))
  Ai = An[0]
  for _ in range(K-1):
    Ai = An[Ai-1]
  return Ai

if loopi > K:
  print(getA(An, K))
else:
  loopstart,loopend = loopdict[str(Ai)]
  k = (K - loopstart) % (loopend - loopstart)
  print(getA(An, loopstart+k))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a=[int(i) - 1 for i in input().split()]
path=[0]
val=-1
while True:
    if a[path[-1]] in path:
        val=a[path[-1]]
        break
    path.append(a[path[-1]])
for i in range(n):
    if path[i] == val:
        print(path[k % (n-i-1)] + 1)
        break

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = input().split()
b = [0]*n
d = {}
ind = 1
num = 0
loop = 1
while num == k:
    if b[ind-1] == 0:
        b[ind-1] = -1
        d[ind] = num
        num += 1
        ind = int(a[ind-1])
    else:
        loop = num-d[ind]
        sup = d[ind]
        break

if k-sup >=0:
    for i in range((k-sup)%loop):
        ind = int(a[ind-1])

print(ind)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = input().split()
b = [0]*n
d = {}
ind = 1
num = 0
while True:
    if b[ind-1] == 0:
        b[ind-1] = -1
        d[ind] = num
        num += 1
        ind = int(a[ind-1])
    else:
        loop = num-d[ind]
        sup = d[ind]
        break


for i in range((k-sup)%loop):
    ind = int(a[ind-1])
print(int(a[ind]))

Submission status: Runtime Error

Solution code:
N,K = map(int, input().split())
A = list(map(int,input().split(" ")))
go = A[0]
B = [1]
while go not in B:
	B.append(go)
	go = A[go-1]
D = B.index(go)
saisho = B[0:D]
mawarutoko = B[D:]
C = (K-len(saisho)) % len(mawarutoko)
if  K > len(B):
	print(mawarutoko[C])
else:
	print(B[K])

Submission status: Runtime Error

Solution code:
def main():
    N,K=map(int,input().split())
    A=list(map(int,input().split()))
    cal=0
    time=[0]*N
    town=[]
    roop=[]

    while time[cal]!=2:
        if time[cal]==0:
            town.append(cal)

        else :
            roop.append(cal)

        time[cal]+=1
        cal=A[cal]-1
    if len(time)>K:
        print(town[K]+1)
        return

    else :
        print(roop[(K-(len(town)-len(roop)))%len(roop)]+1)
        return
main()

Submission status: Runtime Error

Solution code:
def main():
    N,K=map(int,input().split())
    A=list(map(int,input().split()))
    cal=0
    time=[0]*N
    town=[]
    roop=[]

    while time[cal]!=2:
        if time[cal]==0:
            town.append(cal)

        else :
            roop.append(cal)

        time[cal]+=1
        cal=A[cal]-1

    if N>K:
        print(town[K]+1)
        return

    else :
        print(roop[(K-(len(town)-len(roop)))%len(roop)]+1)
        return
main()

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
visit=[1]
pos=0
while True:
    visit.append(a[pos])
    if a[pos]-1 in visit:
        break
    pos=a[pos]-1
loop=[]
looppos=visit[-1]-1
while True:
    loop.append(a[looppos])
    looppos=a[looppos]-1
    if a[looppos] in loop:
        break
print(visit)
print(loop)
if len(visit)>k:
    print(visit[k])
else:
    t=(k%len(visit))
    print(loop[t])

Submission status: Runtime Error

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

n, k = map(int, input().split())
A = list(map(int, input().split()))
a = [0]*n
b = A[0]
per = []
tes = -1

if n <= k:
    for _ in range(k-1):
        b = A[b-1]
    print(b)
    exit()

for _ in range(k+1):
    a[b-1] += 1
    tes += 1
    if 3 in a:
        tes -= len(per)*2
        break
    if 2 in a:
        per.append(b)
    b = A[b-1]

_len = len(per)

ans = (k - tes) % _len

print(per[ans-1])

Submission status: Runtime Error

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

now = 0
cnt = 0
pl = [0]

while k > 0:
    now = tel[now]
    k -= 1
    if now in pl:
        break
    else:
        pl.append(now)
    
loop = now
cnt = 0
while k > 0:
    now = tel[now]
    cnt += 1
    k -= 1
    if now == loop:
        break

k %= cnt
for i in range(k):
    now = tel[now]

print(now+1)

Submission status: Runtime Error

Solution code:
#include <set>
#include <cstdio>
#include <vector>
#include <utility>
#include <iterator>
using namespace std;

int main() {
    unsigned n; unsigned long long k; scanf("%u%llu", &n, &k);
    vector<unsigned> a(n);
    for (unsigned& x : a) scanf("%u", &x), --x;
    set<pair<unsigned, unsigned>> s;
    vector<pair<unsigned, unsigned>> edges;
    pair<unsigned, unsigned> p = make_pair(0U, *a.cbegin());
    pair<set<pair<unsigned, unsigned>>::iterator, bool> _ = make_pair(s.end(), false);
    while ((_ = s.insert(p)).second) edges.emplace_back(p), p = make_pair(p.second, a.at(p.second));
    unsigned c = 0;
    vector<pair<unsigned, unsigned>>::iterator it = edges.begin();
    for (; *it != *_.first; ++c) it = next(it);
    unsigned sz = distance(it, edges.end());
    if (!sz) sz = s.size();
    //printf("s.size()=%u c=%u sz=%u _.first=(%u;%u)\n", s.size(), c, sz, _.first->first, _.first->second); // DEBUG
    printf("%u", (c > --k ? next(edges.begin(), k)->second : next(it, (k - c) % sz)->second) + 1);
    return 0;
}