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())
list1 = list(map(int,input().split()))
visited_town = [[] for i in range(N+1)] #どの町にいつ訪れたか,配列の0あける。
visited_time = [None for i in range(2*N)] #訪れた町の時系列。こっちは0あけない。

visited_town[1].append(0) 
visited_time[0] = 1

cycle_start = -1
cycle_end = -1
cycle_detect = False

for i in range(1,min([K,2*N])):
  next_town = list1[visited_time[i-1]-1]
  visited_town[next_town].append(i)
  visited_time[i] = next_town
  if len(visited_town[next_town]) == 2:
    cycle_start = visited_town[next_town][0]
    cycle_end   = visited_town[next_town][1]
    cycle_detect = True
    break

print(visited_time)

if (!cycle_detect)
  ans = visited_time[K]
  print(ans)
else :   
  syuuki = cycle_end-cycle_start
  cycle = visited_time[cycle_start:cycle_end]
  ans = cycle[(K-cycle_start) % syuuki]
  print(ans)

Submission status: Runtime Error

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

gone = []

isLooped = False


def dfs(index):
    global isLooped
    if index in gone:
        isLooped = True
        return

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


dfs(1)

if isLooped:
    last = gone[-1]
    loopStartIndex = gone.index(Alist[last-1])
    divK = K % len(gone[loopStartIndex:])
    print(Alist[divK])

else:
    print(Alist[K-1])

Submission status: Runtime Error

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

costs = [0] * (N + 1)

if K <= N:
    for i in range(1, K+1):
        loc = A[loc - 1]
    print(loc)

else:
    loc = 1
    for i in range(1, K+1):
        loc = A[loc - 1]

        if costs[loc] > 0:
            break

        costs[loc] = i

    offset = costs[loc]
    loop = i - offset

    K -= offset
    K %= loop

    for _ in range(K):
        loc = A[loc - 1]
    print(loc)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
flag=0
now=0
i=0
count=0
c=[0]*N
r=[0]
c[0]=1
while flag==0:
  now=A[now]-1
  count+=1
  if count==K:
    flag=1
  elif c[now]==1:
    flag=2
  c[now]=1
  r.append(now)
if flag==1:
  print(now+1)
else:
  o=[i for i, x in enumerate(r) if x == now]
  print(A[r[K%(o[1]-o[0])]+o[0]-1])

Submission status: Runtime Error

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

Submission status: Runtime Error

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

ans = 0
b = [1]
for i in range(k):
  if a[b[-1] - 1] in b:
    c = a[b[-1] - 1]
    break
  b.append(a[b[-1] - 1])

d = b[:b.index(c)]
b = b[b.index(c):]

k = k - k // len(b) * len(b) + 1
#print(d,b,k)

for i in d:
    ans = a[i - 1]
    #print(ans)
for i in range(k):
  ans = a[ans - 1]
  #print(ans)
print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
flag=0
now=0
i=0
count=0
c=[0]*N
r=[0]
c[0]=1
while flag==0:
  now=A[now]-1
  count+=1
  if count==K:
    flag=1
  elif c[now]==1:
    flag=2
  c[now]=1
  r.append(now)
print(r)
if flag==1:
  print(now+1)
else:
  o=[i for i, x in enumerate(r) if x == now]
  print(A[r[K%(o[1]-o[0])]+o[0]-1])

Submission status: Runtime Error

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

costs = [0] * (N + 1)

loc = 1
for i in range(1, K+1):
    loc = A[loc - 1]

    if costs[loc] > 0:
        break

    costs[loc] = i

offset = costs[loc]
loop = i - offset

K -= offset
K %= loop

for _ in range(K):
    loc = A[loc - 1]
print(loc)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
a = input(" ")
b = input(" ")
c = []
for i in b:
    c.append(int(i))
d = 0
for j in range(int(a[1])):
    d = c[d] - 1
print(d + 1)

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 p in range(len(c)):
        if c[p]==city:
            break
        if c[p] != city:
            rem+=1
            c1.append(c[p])
    for cit in c1:
        c.remove(cit)
    ##打印
    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().strip().split())
A=list(map(int,input().strip().split()))

l=[1]
x=1
for n in range(N):
    y=A[x-1]
    l.append(y)
    x=y

cnt=[0 for n in range(N)]
for n in range(N):
    cnt[l[n]-1]+=1
    if cnt[l[n]-1]==2:
        temp=n
        break
for m in range(len(l)):
    if l[m]==temp:
        bias=m
        mul=temp-bias+1
        break

if bias>K:
    print(l[K])
else:
    print(l[bias+(K-bias)%mul])

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
N=list(map(int,input().split()))
a={}
 
b=1
a[1]=1
count=0
while(count<=K+1):
  count+=1
  b=N[b-1]
  #print(b)
  if b in a:
    #print(a)
    #print(b)
    #print(count)
    cycle=count-a[b]
    rest=K-count+1
    ans=rest%cycle
    for i in range(ans-1):
      b=N[b-1]
      count+=1
      if count==K+1:
        break
    print(b)
    break
  a[b]=count
  if count==K+1:
    print(b)
    break

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
flag=0
now=0
i=0
count=0
c=[0]*N
r=[0]
while flag==0:
  now=A[now]-1
  count+=1
  if count==K:
    flag=1
  elif c[now]==1:
    flag=2
  c[now]=1
  r.append(now)
print(r)
if flag==1:
  print(now+1)
else:
  o=[i for i, x in enumerate(r) if x == now]
  print(A[r[K%(o[1]-o[0])]+o[0]-1])

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 = [0 for i in range(N)]
    cycle_list = []
    
    cycle = 0
    diff = 0
    counter = 0
    machi = 1
    while counter < N:
        if B_i[machi - 1] == 1:
            diff = cycle_list.index(machi)
            cycle = counter - diff
            cycle_list = cycle_list[diff:]
            break
        else:
            counter += 1
            B_i[machi - 1] = 1
            cycle_list.append(machi)
            machi = A_i[machi - 1]

    if K < N:
        print(cycle_list[K - 1])
    else:
        mod_K = (K - diff) % cycle
        print(cycle_list[mod_K])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

idx = [-1 for _ in range(len(A))]
now = 0
period = 0
bias = 0
tmp = []
for i in range(K):
    tmp.append(now+1)
    if idx[now] == -1:
        idx[now] = i
    else:
        period = i - idx[now]
        cycle = tmp[-period-1:-1]
        bias = i - period
        break
    now = A[now]-1

if K <= bias:
    now = 0
    for _ in range(K):
        now = A[now] - 1
    print(now + 1)
else:
    K -= bias
    K = K % period
    print(cycle[K])

Submission status: Runtime Error

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

route = []
i = 0

while True:
    ne = a[i]

    if i not in route:
        route.append(i)
    else:
        temp = len(route) - len(route[i:])
        if k <= temp:
            print(route[k])
        else:
            print(a[(k-temp)%len(route[i:])])
        break

    i = ne - 1

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import collections


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    N, K = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]

    cur = 1
    c = {}
    route = []
    roop = None
    while (True):
        if cur in c:
            roop = cur
            break
        route.append(cur)
        c[cur] = 1
        cur = A[cur - 1]
    idx = route.index(roop)
    if K <= idx:
        print(route[K])
        return
    route = route[idx:]
    print(route[K % len(route) - idx])
    return


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
 
A = list(map(int,input().split()))
 
now = 0
tele = [0]
tele2 = {0:1}
for i in range(1,K):
  now = A[now] - 1
  if now in tele2:
    num = tele.index(now)
    epoch = i - num
    e_list = tele[num:]
    break
  tele.append(now)
  tele2[now] = 1
amari = (K-num)%epoch
print(e_list[amari] + 1)

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]
idx = []

if k == 1:
    print(a[0])
    exit()
key = True

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

for i in range(n):
    if a[i] == crr:
        idx.append(a[i])
        break

index = idx[0]

if index - 1 == 0:
    zyun1 = zyun
    zyun2 = zyun
else:
    zyun1 = zyun[:index]
    zyun2 = zyun[index:]

# print(zyun1, zyun2)

if len(zyun1) >= k:
    ind = k % len(zyun1)
    if ind == 0:
        print(zyun1[-1])
    else:
        print(zyun1[ind - 1])
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().strip().split())
A=list(map(int,input().strip().split()))

l=[1]
x=1
for n in range(N):
    y=A[x-1]
    l.append(y)
    x=y

x=[0 for n in range(N)]
for n in range(N):
    x[l[n]-1]+=1
    if x[l[n]-1]==2:
        temp=n
        break
for m in range(len(l)):
    if l[m]==temp:
        bias=m
        mul=temp-bias+1
        break

if bias>K:
    print(l[K])
else:
    print(l[bias+(K-bias)%mul])

Submission status: Runtime Error

Solution code:
import numpy as np
N,K=map(int,input().split())
A=list(map(int,input().split()))
def B(i):
  if i==0:
    return 1
  return A[B(i-1)-1]
C=[1]
for i in range(1,N+1):
  if C.count(B(i))==0:
    C.append(B(i))
  else:
    l=C.index(B(i))
    break
if K<=l:
  print(C[K])
else:
  print(C[l+(K+1-l)%(len(C)-l)-1])

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import collections


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    N, K = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]

    cur = 1
    c = {}
    route = []
    roop = None
    while (True):
        if cur in c:
            roop = cur
            break
        route.append(cur)
        c[cur] = 1
        cur = A[cur - 1]
    idx = route.index(roop)
    if K <= idx:
        print(route[k])
        return
    route = route[idx:]
    print(route[K % len(route) - idx])
    return


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
a = list(map(int, input().split()))
t = [1]
x = [0]*n
x[0] = 1
y = 0
z = 0
d = 0
for i in range(k):
    t.append(a[t[i]-1])
    if x[a[t[i]-1]-1] != 0:
        y = x[a[t[i]-1]-1]
        z = i+2
        b = [a[t[i]-1]]
        break
    else:
        x[a[t[i]-1]-1] += i+2
        z = i+2

d = z-y

if d != 0:
    r = (k - y) % d
else:
    r = k - y

for i in range(r+1):
    b.append(a[b[i]-1])

print(b[r+1])

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
a = list(map(int, input().split()))
t = [1]
x = [0]*n
x[0] = 1
y = 0
z = 0
d = 0
for i in range(k):
    t.append(a[t[i]-1])
    if x[a[t[i]-1]-1] != 0:
        y = x[a[t[i]-1]-1]
        z = i+2
        b = [a[t[i]-1]]
        break
    else:
        x[a[t[i]-1]-1] += i+2

d = z-y

if d != 0:
    r = (k - y) % d
else:
    r = k - y

for i in range(r+1):
    b.append(a[b[i]-1])

print(b[r+1])

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 p in range(len(c)):
        if c[p]==city:
            break
        if c[p] != city:
            rem+=1
            c1.append(c[p])
    for cit in c1:
        c.remove(cit)
    ##打印
    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()))

route = []
i = 0

# 方針は合っていたが，
while True:
    ne = a[i]

    if i not in route:
        route.append(i)
    else:
        temp = len(route) - len(route[i:])
        if k < temp:
            print(a[k])
        else:
            print(a[(k-temp)%len(route[i:])])
        break

    i = ne - 1

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
 
A = list(map(int,input().split()))
 
now = 0
tele = [0]
tele2 = dict()
for i in range(1,K):
  now = A[now] - 1
  if now in tele2:
    num = tele.index(now)
    epoch = i - num
    e_list = tele[num:]
    break
  tele.append(now)
  tele2[now] = 1
amari = (K-num)%epoch
print(e_list[amari] + 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

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

if k < modC:
    print(t[k] + 1)
else:
    print(t[modC + modK] + 1)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
if __name__=="__main__":
    N, K = map(int, input().split(' '))
    _town_list = input().split(' ')
    town_list = [int(n) for n in _town_list]

    next_town = town_list[0]
    visited_town = set()
    visited_town.add(1)
    visited_town.add(next_town)
    lst_visited_town = [1]
    lst_visited_town.append(next_town)
    counter = 1

    while True:
        counter += 1
        next_town = town_list[next_town-1]
        if counter == K:
            print(next_town)
            break
        if next_town in visited_town:
            repeated_town_idx = lst_visited_town.index(next_town)
            loop_num = counter - repeated_town_idx
            print(visited_town[(K-repeated_town_idx)%loop_num + repeated_town_idx])
            break
        lst_visited_town.append(next_town)
        visited_town.add(next_town)

Submission status: Runtime Error

Solution code:
def solve():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    lis = [1]
    i = 1
    while True:
        i = A[i-1]
        print(K)
        print(lis)
        if not i in lis:
            lis.append(i)
        else:
            lis = lis[lis.index(i):]
            ind = K % len(lis)
            if ind != 0:
                return lis[ind-1]
            else:
                return lis[-1]

        if K == 0:
            return i
        
        K -= 1


if __name__ == '__main__':
    print(solve())

Submission status: Runtime Error

Solution code:
if __name__=="__main__":
    N, K = map(int, input().split(' '))
    _town_list = input().split(' ')
    town_list = [int(n) for n in _town_list]

    next_town = town_list[0]
    visited_town = set()
    visited_town.add(1)
    visited_town.add(next_town)
    lst_visited_town = [1]
    lst_visited_town.append(next_town)
    counter = 1

    while True:
        counter += 1
        next_town = town_list[next_town-1]
        if counter == K:
            print(next_town)
            break
        if next_town in visited_town:
            repeated_town_idx = lst_visited_town.index(next_town)
            loop_num = counter - repeated_town_idx
            print(visited_town[(K-repeated_town_idx)%loop_num + repeated_town_idx])
            break
        lst_visited_town.append(next_town)
        visited_town.add(next_town)

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
a = [0] + list(map(int,input().split()))

journey = [1]

for i in range(N):
    nxt = a[journey[-1]]
    journey.append(nxt)

if K < N:
    print(journey[K])
    exit()

loop_start = N-1
loop_end   = N

finished = False
for i in range(N):
    for j in range(i,N+1):
        if journey[i] == journey[j]:
            loop_start = i
            loop_end   = j
            finished = True
            break
    if finished:
        break

period = loop_end - loop_start

ans = (K - loop_start) % period
print(ans)

Submission status: Runtime Error

Solution code:

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

#n=6
#k=727202214173249351
#a=[6, 5, 2, 5, 3, 2]

#n=4
#k=5
#a=[3,2,4,1]

#if n<k:
if 1==1:
    ai=1
    aj=set()
    for i in range(min(n,k)):
        aim=ai
        ai=a[ai-1]
        if ai in aj:
            ic2=i
            ai2=ai
            break
        else:
            aj.add(ai)

    ai=1
    for i in range(min(n,k)):
        ai=a[ai-1]
        if ai==ai2:
            ic1=i
            break

    icyc=ic2-ic1
    k2=(k-ic1)%icyc+ic1
else:
    ic1=0
    icyc=1
    k2=k
    
ai=1
for i in range(k2):
    ai=a[ai-1]
        
print(ai)

Submission status: Runtime Error

Solution code:
import math

n, k = map(int, input().split(" "))
aL = list(map(int, input().split(" ")))
aFL = [False for _ in range(n)]

crnt = 1
cnt1 = 0
while True:
    if aFL[crnt - 1]:
        break
    cnt1 += 1
    aFL[crnt - 1] = True
    crnt = aL[crnt - 1]

wCrnt = crnt
cnt2 = 0
while True:
    crnt = aL[crnt - 1]
    cnt2 += 1
    if crnt == wCrnt:
        break

gp = cnt1 - cnt2

cr = crnt
for i in range((k - gp) % n):
    cr = aL[cr]

print(aL[aL[cr - 1]])

Submission status: Runtime Error

Solution code:
import sys
def inpl(): return list(map(int, sys.stdin.readline().split()))
N, K = map(int, sys.stdin.readline().split())
A = inpl()
dic = {}
for i in range(N):
    dic[i+1] = A[i]
i = 1
visit = []
visit_set = set()
while i not in visit:
    visit.append(i)
    i = dic[i]
find = visit.index(i)
if K < find:
    print(visit[K])
else:
    visit = visit[find:]
    length = len(visit) - find
    K = (K-find) % length
    print(visit[K])

Submission status: Runtime Error

Solution code:
import copy
N,K = list(map(int, input().split()))
 
A = list(map(int, input().split()))
 
count = [0]
Check = [0] * N
for i in range(K):
    count.append(A[count[-1]]-1)
    print(count)
    if(Check[count[-1]-1] == 1):
        break
 
    Check[count[-1]-1] = 1
    i += 1

saisyo = count.index(count[-1]) + 1

if(K > saisyo):
    loop_kazu = len(count) - saisyo
    K_loop = K - saisyo
 
    ans_index = K_loop % loop_kazu
    ans = count[saisyo + ans_index] + 1
 
    print(ans)

else:
    print(count[K-1]+1)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
As = list(map(int, input().split()))
maps = {}

for i, a in enumerate(As):
    maps[i] = a - 1

probs = [0] * n
p = 0  # 現在位置
target = 0  # はじめて2回出現する場所
h = 0  # ターゲットの初回出現時のワープ回数
t = 0  # ターゲットの2回目の出現時のワープ回数

# はじめて2回出現する場所(target)と、その時点でのワープ回数を取得
for i in range(n):
    if (p == maps[p]):
        target = p
        t = i
        break
    probs[p] += 1
    if (probs[p] == 2):
        target = p
        t = i
        break
    p = maps[p]

# 初回出現位置を取得(めんどうくさいのでもう一回回した。)
p = 0
for i in range(n):
    if (p == target):
        h = i
        break
    p = maps[p]

s = t - h  # 周期
d = (k - h) % s  # targetに到着後にワープすべき回数

# 実際に必要な回数だけワープ
p = 0
for i in range(h + d):
    p = maps[p]

print(p + 1)

Submission status: Runtime Error

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

m = {}
for i, a in enumerate(A):
    m[i+1] = a

visited = []
cycle = set()
current_city = 1
visited.append(current_city)
cycle.add(current_city)
cycle_start_index = -1
while 1:
    current_city = m[current_city]
    if current_city in cycle:
        cycle_start_index = visited.index(current_city)
        break
    else:
        visited.append(current_city)
        cycle.add(current_city)

cycle_before = visited[:cycle_start_index]
cycle_after = visited[cycle_start_index:]
if len(cycle_before) > K:
    print(cycle_after[(K - len(cycle_before)) % len(cycle_after)])
else:
    print(cycle_before[K - 1])

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
N=list(map(int,input().split()))
a={}
 
b=1
a[1]=1
count=1
while(True):
  count+=1
  b=N[b-1]
  #print(b)
  if b in a:
    #print(a)
    #print(b)
    #print(count)
    cycle=count-a[b]
    rest=K-count+1
    ans=rest%cycle
    for i in range(ans-1):
      b=N[b-1]
    print(b)
    break
  a[b]=count
if count==K+1:
  print(b)
  break

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]
idx = []

if k == 1:
    print(a[0])
    exit()
key = True

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

for i in range(n):
    if a[i] == crr:
        idx.append(a[i])
        break

index = idx[0]

if index - 1 == 0:
    zyun1 = zyun
    zyun2 = zyun
else:
    zyun1 = zyun[:index]
    zyun2 = zyun[index:]

# print(zyun1, zyun2)

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

Submission status: Runtime Error

Solution code:
import math

n, k = map(int, input().split(" "))
aL = list(map(int, input().split(" ")))
aFL = [False for _ in range(n)]

crnt = 1
cnt1 = 0
while True:
    if aFL[crnt - 1]:
        break
    cnt1 += 1
    aFL[crnt - 1] = True
    crnt = aL[crnt - 1]

wCrnt = crnt
cnt2 = 0
while True:
    crnt = aL[crnt - 1]
    cnt2 += 1
    if crnt == wCrnt:
        break

gp = cnt1 - cnt2

cr = wCrnt
for i in range((k - gp) % n):
    cr = aL[cr]

print(aL[cr])

Submission status: Runtime Error

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

stack = [1]
s = {1}

def dfs(a, k):
  global stack
  global s
  if k == 0:
    return a
  next_a = A[a]
  if next_a in s:
    idx = stack.index(next_a)
    n = len(stack)
    k = (k - 1)%(n - idx)
    return stack[idx + k]
  else:
    stack.append(next_a)
    s.add(next_a)
    res = dfs(next_a, k-1)
  return res

print(dfs(1, K))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
towns = [int(i) for i in input().split()]
arrivedList = [1]
loopCount = 0
previous = 0
for i in range(len(towns)):
    idx = arrivedList[len(arrivedList) - 1] - 1
    current = towns[idx]
    if arrivedList.count(current) == 0:
        arrivedList.append(current)
    else:
        previous = len(arrivedList) - (len(arrivedList)-arrivedList.index(current))
        loopCount = len(arrivedList)-arrivedList.index(current)
        break
    if i == K - 1:
        print(arrivedList[len(arrivedList) - 1])
        exit()
remain = K % loopCount - previous
loopList = arrivedList[previous: previous + loopCount]

print(loopList[remain])

Submission status: Runtime Error

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

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

now=1

ls=[1]
count=0
for i in range(K):
    count=i
    now=A[now-1]
    if now in ls:
        break
    ls.append(now)
    
# print(ls)
front_index=[i for i, x in enumerate(ls) if x == A[now-1]][-1]-1
end_index=len(ls)-1

# print(front_index)
# print(end_index)


sa=end_index-front_index+1

# print(sa)

k=K-front_index

k-=(k//sa)*sa


print(ls[front_index+k])

Submission status: Runtime Error

Solution code:
import sys

def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]


def main():
    N, K = MI()
    A = LI()
    A.insert(0, 0)
    x = 1
    y = 0
    roop=1000
    l = [0]*roop
    for i in range(roop):
        x = A[x]
        l[i]=x
    ln = len(set(l))
    for i in range(N):
        for j in range(i+1,N+1):
            if l[i] == l[j]:
                y = j-i
                break
        if y != 0:
            break
    """print("l",l)
    print("ln",ln)
    print("y",y)
    print("l[K-1]",l[K-1])"""
    if K <= N:
        print(l[K-1])
    else:
        amari = (K - ln)%y
        if amari == 0:
            print(l[ln-1])
        else:
            ans=l[ln-1-(y-amari)]
            print(ans)

    


if __name__ == "__main__":
	main()

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]

if k == 1:
    print(a[0])
    exit()
key = True

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

for i in range(n):
    if a[i] == crr:
        index = crr
        break


if index - 1 == 0:
    zyun1 = zyun
    zyun2 = zyun
else:
    zyun1 = zyun[:index]
    zyun2 = zyun[index:]

# print(zyun1, zyun2)

if len(zyun1) >= k:
    ind = len(zyun1) % k
    if ind == 0:
        print(zyun1[-1])
    else:
        print(zyun1[ind - 1])
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())
towns = [int(i) for i in input().split()]
arrivedList = [1]
loopCount = 0
previous = 0
for i in range(len(towns)):
    idx = arrivedList[len(arrivedList) - 1] - 1
    current = towns[idx]
    if arrivedList.count(current) == 0:
        arrivedList.append(current)
    else:
        previous = len(arrivedList) - (len(arrivedList)-arrivedList.index(current))
        loopCount = len(arrivedList)-arrivedList.index(current)
        print(previous,current, loopCount, arrivedList)
        break
    if i == K - 1:
        print(arrivedList[len(arrivedList) - 1])
        exit()
remain = K % loopCount - previous
loopList = arrivedList[previous: previous + loopCount]
print(loopList[remain])

Submission status: Runtime Error

Solution code:
N,K = map(int, input().split())
A =[0]
B=list(map(int, input().split()))
for m in range(N):
    A.append(B[m])
place=set([])
p=[]
i=1
count=0
while i not in place:
    place.add(i)
    p.append(i)
    i=A[i]
    count+=1
if count>=K:
    print(p[K])
else:
    loop=[i]
    start=i
    j=A[i]
    count+=1
    while j!=start:
        loop.append(j)
        j=A[j]
        count+=1
    if count>=K:
        print(loop[K-len(p)])
    else:
        num=(K-count)%len(loop)
        print(loop[0])

Submission status: Runtime Error

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

iter = 0
path = [0]
while iter < K:
    path.append(A[path[-1]] - 1)
    if path[-1] in path[:-1] and iter > 0:
        break
    iter += 1
"""
print(path)
loop_start = path.index(path[-1])
loop_len = len(path[loop_start : -1])
print(loop_start)
print(path[loop_start : -1])
print(loop_len)"""
goal = ((K - loop_start) % loop_len) + loop_start
print(A[goal])

Submission status: Runtime Error

Solution code:
import copy
N,K = list(map(int, input().split()))
 
A = list(map(int, input().split()))
 
count = [0]
Check = [0] * N
for i in range(K):
    count.append(A[count[-1]])
    print(count)
    if(Check[count[-1]] == 1):
        break
 
    Check[count[-1]] = 1
    i += 1
 
 
saisyo = count.index(count[-1]) + 1

if(K > saisyo):
    loop_kazu = len(count) - saisyo
    K_loop = K - saisyo
 
    ans_index = K_loop % loop_kazu
    ans = count[saisyo + ans_index] + 1
 
    print(ans)

else:
    print(count[K] + 1)