Problem:


Score: 400 points

Problem Statement

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

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

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

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

Constraints

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

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

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

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

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

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2



Sample input:
4 5
3 2 4 1


Sample output:
4

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, k = map(int, input().split())
    A = list(map(int, input().split()))

    tree = [[] for _ in range(n)]
    for idx, a in enumerate(A):
        tree[idx].append(a - 1)

    start = []
    depth = [0 for _ in range(n)]

    def dfs(v, p, d, cnt):
        depth[v] = d
        for u in tree[v]:
            if u == p:
                continue

            if visited[u]:
                start.append([u + 1, depth[u], cnt + 1])
                return
            else:
                visited[u] = True
                dfs(u, v, d + 1, cnt + 1)
        return

    visited = [False for _ in range(n)]
    visited[0] = True
    dfs(0, -1, 0, 0)

    if not start:
        res = 1 if k % 2 != 0 else A[0]
        print(res)
    else:
        if k <= start[0][1]:
            print(depth.index(k) + 1)
        else:
            cnt = (k - start[0][1]) % (start[0][2] - start[0][1])
            res = start[0][1] + cnt
            print(depth.index(res) + 1)


if __name__ == '__main__':
    resolve()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import math
from collections import defaultdict

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

ha = defaultdict(int)
ans = defaultdict(int)
s = set()
s.add(1)
ss = set()
mod = 0
mod2 = 0
next = 0
ind = 0
flag = 0
while  True:
    if A[next] in s and flag == 0:
        flag = 1
        ha[0] = A[next]
        ans[0] = A[next]
        ss.add(A[next])
        ind = 0
        mod += 1
        continue
        # next = A[next] - 1 
    elif flag == 1:
        ans[ind+1] = A[next]
        ss.add(A[next])
        next = A[next] - 1
        if A[next] in ss :
            mod2 += 1
            break
        mod2 += 1
        ind += 1
        continue

    ha[ind+1] = A[next]
    s.add(A[next])
    next = A[next] - 1
    mod += 1
    ind += 1

if mod > K :
    print(ha[K % mod])
else:
    if K - mod <0 :
        print(ha[K])
    else:
        print(ans[(K-mod)%mod2])

Submission status: Wrong Answer

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

limit = K
now = 1
log = []

while limit > 0 and now not in log:
    if 1 not in log:
        log.append(1)
    #print("通過1",now,limit,log)
    now = A[now - 1]
    log.append(now)
    limit -= 1

if limit > 0:
    #print("通過2",now,limit,log)
    limit = limit % len(log[log.index(now) - 1:])

while limit > 0:
    #print("通過3",now)
    now = A[now - 1]
    limit -= 1
now = A[now - 1]

print(now)

Submission status: Wrong Answer

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

nxt = 1
visited_num = [1]
visited = [False] * N
visited[0] = True
first = []
repeat = []
for _ in range(N):
    nxt = A[nxt - 1]
    visited_num.append(nxt)
    if visited[nxt - 1]:
        i = visited_num.index(nxt)
        if i != 0:
            first = visited_num[:i]
            repeat = visited_num[i:]
        break
    else:
        visited[nxt - 1] = True

if 0 == len(repeat):
    ans = A[K % len(visited_num)]
else:
    ans = A[(K - len(first) + 1) % len(repeat)]
print(ans)

Submission status: Wrong Answer

Solution code:
from decimal import *
N, K = map(int, input().split())
# print(K)
A_list = list(map(int, input().split()))
# print(A_list)
# N, K = 6, 727202214173249351
# A_list = [6, 5, 2, 5, 3, 2]
# N, K = 4, 11
# A_list = [2,3,1,2]
Place = 0
N_list = [0 for i in range(N)]
Count_Start = 0
Count_Stop = 0
while True:
    Count_Start += 1
    if N_list[Place] != 0:
        Count_Stop = Count_Start
        Count_Start = N_list[Place]
        break
    N_list[Place] += Count_Start
    Place = A_list[Place] -1


Loop_Count = Count_Stop - Count_Start
# print(Loop_Count)
A = int(Decimal(Decimal(K)/Loop_Count))
# print(A)
K -= (int(Decimal(Decimal(K)/Loop_Count)) -1) * Loop_Count
# print(K)

Place = 0
for i in range(K):
    Place = A_list[Place] - 1
    # print(Place)
print(Place+1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(20000)

dest_array = []


def move_destination(dest, counta, limit, teleporte_destination):

    # print('目的地は{}'.format(dest))
    # print('次に行くのは{}'.format(teleporte_destination[dest]))
    # print('カウントは{}'.format(counta))
    if counta >= limit:
        print(dest)
        return
    loop_number = None
    if dest_array.count(dest) == 1:
        loop_number = counta - dest_array.index(dest)
        # print('スキップ発生')
    if loop_number is not None:
        # print('スキップ前{}'.format(limit))
        # print(limit)
        # print(loop_number)
        limit = limit % loop_number
        # print('スキップ後{}'.format(limit))

    dest_array.append(teleporte_destination[dest])

    move_destination(
        teleporte_destination[dest], counta+1, limit, teleporte_destination)


town_number, limit = map(int, input().split())  # 街の数 K回
teleporte_destination = list(map(int, input().split()))
teleporte_destination = [0] + teleporte_destination  # インデックスを合わせるため
# print(teleporte_destination)
move_destination(1, 0, limit, teleporte_destination)

Submission status: Wrong Answer

Solution code:
N, K  = map(int, input().split())
A = [int(x) for x in input().split()]
count = [0] * N
t = A[0]
count[0] = 1
for i in range(N+1): 
    j = A[t-1]
    t = j
    if count[t-1] > 0:
        K = K - count[t-1] + 1
        K = K % (i+2 - count[t-1] + 1)
        break
    count[t-1] = i+2
t = A[0]
j = 0
for i in range(K):
    j = A[t-1]
    t = A[j-1]
print(t)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

def func1(lst, value):
    return [i for i, x in enumerate(lst) if x == value]
  
temp=1
trace=deque()
trace.append(1)
#trace=[1]
circle=[]
for i in range(K):
  temp=A[temp-1]
  ans=func1(trace,temp)
  if len(ans)==1:
    #print(temp)
    #print(trace.index(temp))
    #start=trace.index(temp)
    for _ in range(ans[0]):
      trace.popleft()
    #circle=trace[ans[0]:]
    circle.append(1)
    #print(circle)
    break
  trace.append(temp)
  #print("temp",temp)
#print((K-i)%len(circle)-1)
if len(circle)!=0:
  amari=(K-i)%len(trace)
  print(trace[amari])
else:
  print(temp)

Submission status: Wrong Answer

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

ans = A[0]

d = {0:1, ans -1:1}
#移動する可能性がある街の個数uを出す
for i in range(N):
  #print(ans)
  ans = A[ans - 1]
  if ans -1 not in d:
    d[ans -1] = 1
  else:
    d[ans - 1] += 1
  
#print("d", d, len(d))
u = len(d)

cnt_ = 0
#1回しかこない地点は何個
for i in d.values():
  if i == 1:
    cnt_ += 1

if cnt_ != 0:
  u = u - cnt_
  a = (K - cnt_) % u
  
  ans = A[0]
  for i in range(cnt_ - 1):
    ans = A[ans - 1]

else:
  a = K % u
  ans = A[0]
  
if a == 0:
  a = u

#print("a", a)

for i in range(a - cnt_ - 1):
  #print(i, ans)
  ans = A[ans - 1]
print(ans)

Submission status: Wrong Answer

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 len(townLoop) > 2 and 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: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(100000000)

stp = -1 
def main():
    n, k = map(int, readline().split())
    a = [int(i)-1 for i in readline().split()]

    order = []
    ex = set()
    def dfs(node):
        global stp
        order.append(node)
        ex.add(node)
        nx = a[node]
        if nx in ex:
            stp = nx
            return
        dfs(nx)
    dfs(0)

    cnt = order.index(stp)
    if k <= cnt:
        print(order[k-1]+1)
    else:    
        m = len(order[cnt:])
        idx = (k-cnt)%m
        print(order[cnt:][idx]+1)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

aList = list(map(int, input().split()))
seen = []
tsugi = 0
flag = False
for i in range(k):
  tsugi = aList[tsugi]-1
  if tsugi not in seen:
    seen.append(tsugi)
  else:
    index = seen.index(tsugi)
    length = i - index
    flag = True
    break
if flag:
  print(seen[index + (k-index)%length-1]+1)
else:
  print(tsugi+1)

Submission status: Wrong Answer

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

b = A[0]
count = 1

X = []
flag = 0
loop = 0
ans = 0

if A[0] == 1:
    ans = 1

else:   
    #print("a")
    for i in range(K):
        c = A[b-1]
        b = c
        l = len(X)
        for j in range(l):
            if b == X[j-1]:
                loop = i - j + 1
                flag = 1
                Z = i + 1
                #print(loop)
                break


        if flag == 1:
            break
        else:
            X.append(b)
            #print(X)
    if loop ==1:
        ans =A[Z]
    elif loop ==0:
        ans = b
    else:        
        #print(loop)        
        Y = K%loop
        #print(Y)
        #print(Z)
        #print(Z+Y-1-loop)
        ans = A[Z+Y-1-loop]

print(ans)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
lis = list(map(int, input().split()))
res = [1]
for i in range(n):
    a = lis[res[-1]-1]
    if a in res:
        x, y = res.index(a), i+1
        mm = (m - x) % (y - x)
        print(res[x + mm])
        exit()
    res.append(a)

Submission status: Wrong Answer

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

mod = [0]
idx = A[0]

for i in range(n):
    if idx in mod:
        idx = mod.index(idx)
        break
    mod.append(idx)
    idx = A[idx]

r = len(mod) - idx
k -= idx
mod = mod[idx:]

print(mod[k % r] + 1)

Submission status: Wrong Answer

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

    l = [0]
    for i in range(n):
        b = a[l[i]]-1
        l.append(b)
        if l[i] >= l[i+1]:
            break
            
    ind = l[k%(len(l)-1)]
    print(l)
    return ind+1


print(solve())

Submission status: Wrong Answer

Solution code:
n, k_in=map(int, input().split())
a_l=list(map(int, input().split()))

def f(s):
    a = s
    b = s
    i=1
    while True:
        a = a_l[a-1]
        a = a_l[a-1]
        b = a_l[b-1]
        if a == b:
            break
        i+=1

    j=1
    a = a_l[0]
    while True:
        a = a_l[a-1]
        b = a_l[b-1]
        if a == b:
            break
        j+=1

    k=1
    while True:
        a = a_l[a-1]
        a = a_l[a-1]
        b = a_l[b-1]
        if a == b:
            break
        k+=1

    return j, k

lam, myu = f(a_l[0])
# print(lam,myu)
pos=[]
pos.append(a_l[0])
for i in range(n):
    pos.append(a_l[pos[i]-1])

if k_in<=lam:
    print(pos[k_in])
else:
    k_in=(k_in-lam)%myu
    print(pos[lam+k_in-1])

Submission status: Wrong Answer

Solution code:
no_towns, no_moves = list(map(int, input().split()))

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


pos = moves[0]
chain_len = len(set(moves))-1
chain = [moves[min(moves)-1]]
while len(chain) < chain_len+1:
    pos = moves[pos-1]
    chain.append(pos)
chain = chain[1:]

current_pos = moves[0]
while current_pos != chain[0]:
    current_pos = moves[current_pos-1]
    no_moves -= 1

extra_pos = no_moves % chain_len

if extra_pos > 0:
    current_pos = chain.pop()
    for i in range(extra_pos):
        current_pos = moves[current_pos-1]

print(current_pos)

Submission status: Wrong Answer

Solution code:

def q4():
    N, K = [int(i) for i in input().split(" ")]
    A = [-1] + [int(i) for i in input().split(" ")]

    arrived = []
    arrived_set = set()
    current = 1
    loop_start_station = -1
    while True:
        arrived.append(current)
        arrived_set.add(current)
        current = A[current]
        if current in arrived_set:
            loop_start_station = arrived.index(current)
            break

    if K <= loop_start_station:
        print(arrived[K])
    K = K - loop_start_station
    arrived = arrived[loop_start_station:]
    K = K % len(arrived)
    print(arrived[K])
        

q4()

Submission status: Wrong Answer

Solution code:
"""
最初からループ
4 5
3 2 4 1
out 4: ok

途中からループ

ループまで行かず
6 1
6 5 2 5 3 2

out 6: ok

ループまで行く
6 727202214173249351
6 5 2 5 3 2

out: 2 : ok

"""

def looptime(n, a):
    for i in range(n):
        loop = 0
        start = i
        now = i

        time = 0

        while(loop < n):
            now = a[now]
            loop += 1
            now -= 1

            if now == start:
                return i+1, loop

def start_loop(goal, a):
    loop = 0
    now = 0

    time = 0

    while(loop < n):
        now = a[now]
        loop += 1
        now -= 1

        if now == goal-1:
            return loop

if __name__ == '__main__':

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

    start, loop = looptime(n, a)
    how = start_loop(start, a)
    point = k%loop
    """
    #print(start, loop, point, how)

    if how == loop:
        # startからループ開始
        time = 0
        now = 0
        while(time < point):
            now = a[now]
            now -= 1
            time += 1
        print(now+1)

    else:
        # 途中からループ開始
        if how > k:
            time = 0
            now = 0
            while(time < k):
                now = a[now]
                now -= 1
                time += 1
            print(now+1)

        else:
            time = 0
            now = start-1
            point = (point+how)%loop
            while(time < point-1):
                now = a[now]
                now -= 1
                time += 1
            print(now+1)
    """

Submission status: Wrong Answer

Solution code:
s = input().split()
N = int(s[0])
K = int(s[1])

s2 = input().split()
A = []
for i in range(N):
  A.append(int(s2[i]))
  
now = 1
root = []
root.append(now)

for k in range(N):
  new = A[now-1]
  if new in root:
    Ka = K - root.index(new)
    new_root = root[root.index(new):]
    print(new_root[Ka%len(new_root)])
    break
  else:
    now = new
    root.append(new)

Submission status: Wrong Answer

Solution code:
def function(arg1, arg2):
    N,K = map(int, arg1.split())
    teleportes = list(map(int, arg2.split()))
    checked = [0] * len(teleportes) # 訪れた街にチェック

    i = 0
    c = 1
    while True :
        nextTerminal = teleportes[i] - 1
        if checked[i] == 0:
            checked[i] = c # 何番目に訪れたか
            i = nextTerminal
            c += 1
        else:
            loops = c - checked[i] # 以前訪れてから何回旅したか
            break
    
    if K <= i:
        goal = teleportes[K]
    else:
        r = (K-(checked[i]-1))%loops
        nextTerminal = 0
        while nextTerminal != i:
            nextTerminal = teleportes[nextTerminal] - 1
        k = 0
        while k in range(r):
            nextTerminal = teleportes[nextTerminal] - 1
            k+=1
        goal = nextTerminal + 1
    return str(goal)

if __name__ == '__main__':
    print(function(input(),input()))

Submission status: Wrong Answer

Solution code:
import sys
import itertools as iter
import math as m

def main():
    N, K = list(map(int, input().split()))
    A = [-1]
    A += [int(i) for i in input().split()]
    L = [0] * (N + 1)

    L[1] = 1
    x = A[1]
    L[x] = 1
    for i in range(K-1):
        x = A[x]
        if L[x] == 2:
            #print(L)
            lc = (K-i) % L.count(2)
            for _ in range(lc):
                x = A[x]
            print(A[x])
            return
        else:
            L[x] += 1
    print(x)

def main2():
    N, K = list(map(int, input().split()))
    A = [-1]
    A += [int(i) for i in input().split()]

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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
DEBUG = False

import time

N, K = map(int, input().split())
A = [int(i)-1 for i in input().split()]

visited = [False] * N
next = A[0]
visited[0] = True
K -= 1
count = 1
while not visited[next]:
    if DEBUG:
        print("next: {}".format(next))
        print("visited: {}".format(visited))
        time.sleep(0.1)
    visited[next] = True
    next = A[next]
    K -= 1
    count += 1

K -= 1
count += 1
now = next

K %= count

if DEBUG:
    print("now: {}, count: {}, K: {}".format(now, count, K))

while K > 0:
    if DEBUG:
        print("now: {}".format(now))
    now = A[now]
    K -= 1

print(A[now]+1)

Submission status: Wrong Answer

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

i = 1
dct = {}
for j in range(N):
    dct[j+1] = 0
rts = []
for _ in range(N):
    if dct[i] == 1:
        break
    else:
        dct[i]+=1
        rts.append(i)
        i = As[i-1]
before = rts.index(i)
new = rts[before:]
print(new[(K - before) % (len(rts)-before)])

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
point = [int(i) for i in input().split()]
lst = [1]
i = 1
while True:
    i = point[i - 1]
    if i not in lst:
        lst.append(i)
    else:
        print(i)
        break
for j in range(len(lst)):
    if lst[j] == i:
        break
la = lst[:j]
re = lst[j:]
x = K - len(la)
y = x % len(re)
print(re[y])

Submission status: Wrong Answer

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

flag=[0]*n
place=[0]*n
p=0
for i in range(len(a_list)+1):
    if flag[p]>0:
        rep=i
        replis=place[flag[p]-1:i]
        st=p+1
        break
        
    else:
        place[i]=p+1
        flag[p]=i+1
        p=a_list[p]-1

if i == n:
    print(place[-1])
else:
    print(replis[(k-st-len(replis))%len(replis)])

Submission status: Wrong Answer

Solution code:
N, K  = list(map(int,input().split()))
A  = list(map(int,input().split()))
A = [-1]+A
reached = []
dic = {}
now = A[1]
count=0
while now not in reached:
  reached.append(now)
  
  count+=1
  dic[now] = count-1
  now = A[now]
  #print(dic)
ind = dic[now]#reached.index(now)
#pre = reached[:ind]
#loop = reached[ind:]
#print(reached)
if K<=ind-1:
  print(reached[K])
else:
  K -= ind#(len(pre))
  K = K%(count-ind)#len(loop)
  #print((count-ind))
  #print(loop[K])
  #print(dic)
  print(reached[ind+K-1])

Submission status: Wrong Answer

Solution code:
import numpy as np
N, K = list(map(int, input().split()))
A = np.array(list(map(int, input().split()))) - 1
mem = np.zeros((N, 2))

c = 0
for k in range(1, K+1):
    c = A[c]
    mem[c][0] += 1
    if np.any(mem>1):
        T = k - mem[c][1]
        break
    mem[c][1] = k
    
if k == K:
    print(c+1)
else:
    iterN = int((K - k) % T)
    if iterN > 0:
        for i in range(iterN):
            c = A[c]
    print(c+1)

Submission status: Wrong Answer

Solution code:
N, K = input().split()
AN = input().split()
K = int(K) % int(N)
i = 1
N1 = int(AN[0])
NX = AN[N1-1]
while i < int(K):
    NX = AN[N1-1]
    N1 = int(NX)
    i += 1
print(NX)

Submission status: Wrong Answer

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

V = [0 for i in range(n)]
P = [-1 for i in range(n)]
cp = 1
t = 0
while 1:
    #print('V = ', V)
    V[cp - 1] += 1
    if V[cp - 1] < 2:
        P[cp - 1] = t
    else:
        break
    cp = A[cp - 1]
    t += 1

pret = P[cp - 1]
t = t - pret
#print('pret = ', pret)
#print('t = ', t)
#print('P = ', P)

if k <= pret:
    pass
else:
    k = k - pret
    P = list(map(lambda x: x - pret, P))
#print('P = ', P)

l = k % t
for i in range(n):
    if P[i] == l:
        ans = i + 1
        break
    else:
        pass
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
sub = [0]*n
ans = 1
cir = 0
a = 0
for i in range(n):
  sub[i] = ans
  if A[ans-1] in sub:
    a = sub.index(A[ans-1])
    cir = i+1 - a
    break
  else:
    ans = A[ans-1]
if sub[-1] != 0:
  print(sub[k%n])
  exit(0)
print(sub[a + (k - a) % cir])

Submission status: Wrong Answer

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

new_a = []
city = 1
ipponmichi_last = 1
while True:

    if city in new_a:
        ipponmichi_last  = city
        break
    else:
        new_a.append(city)
        city = a[city - 1]

lastcitynum  = 0
for i, city in enumerate(new_a):
    if city == ipponmichi_last:
        lastcitynum = i
        break

if a[0] == 1:
    print(1)
else:
    print(new_a[lastcitynum:][(k-lastcitynum) % (len(new_a) - lastcitynum)])

Submission status: Wrong Answer

Solution code:

n,k=map(int,input().split())
a=list(map(int,input().split()))
b=[False]*n
c=[0]*n
i=0
b[0]=True
j=0
count=1
ch=True
while ch:
    temp=a[i]-1
    if b[temp]==True:
        ch=False
        count-=c[temp]
    else:
        i=temp
        b[temp]=True
        c[temp]=count
        count+=1
    #print(temp)
#print(count)
i=temp
if k<c[temp]:
    for j in range (k):
        temp=a[i]-1
        i=temp
    i+=1
    print(i)
else:
    k-=c[temp]
    k%=count
    for j in range (k):
        temp=a[i]-1
        i=temp
    i+=1
    print(i)

Submission status: Wrong Answer

Solution code:
n, k_in=map(int, input().split())
a_l=list(map(int, input().split()))

def f(s):
    a = s
    b = s
    i=1
    while True:
        a = a_l[a-1]
        a = a_l[a-1]
        b = a_l[b-1]
        if a == b:
            break
        i+=1

    j=1
    a = a_l[0]
    while True:
        a = a_l[a-1]
        b = a_l[b-1]
        if a == b:
            break
        j+=1

    k=1
    while True:
        a = a_l[a-1]
        a = a_l[a-1]
        b = a_l[b-1]
        if a == b:
            break
        k+=1

    return j, k

lam, myu = f(a_l[0])
# print(lam,myu)
pos=[]
pos.append(a_l[0])
for i in range(n):
    pos.append(a_l[pos[i]-1])

if k_in<=lam:
    print(pos[k_in-1])
else:
    k_in=(k_in-lam)%myu
    print(pos[lam+k_in-1])

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import math
from collections import defaultdict

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

ha = defaultdict(int)
ans = defaultdict(int)
s = set()
s.add(1)
ss = set()
mod = 0
mod2 = 0
next = 0
ind = 0
flag = 0
while  True:
    if A[next] in s and flag == 0:
        flag = 1
        ha[0] = A[next]
        ans[0] = A[next]
        ss.add(A[next])
        ind = 0
        mod += 1
        continue
        # next = A[next] - 1 
    elif flag == 1:
        ans[ind+1] = A[next]
        ss.add(A[next])
        next = A[next] - 1
        if A[next] in ss :
            mod2 += 1
            break
        mod2 += 1
        ind += 1
        continue

    ha[ind+1] = A[next]
    s.add(A[next])
    next = A[next] - 1
    mod += 1
    ind += 1

if mod == mod2 :
    print(ha[K % mod])
else:
    if K - mod <0 :
        print(ha[K])
    else:
        print(ans[(K-mod)%mod2])

Submission status: Wrong Answer

Solution code:
def resolve():
  N, K = map(int, input().split(" "))
  A = [int(x) - 1 for x in input().split(" ")]

  history = []
  current = 0
  while True:
    history.append(current)
    current = A[current]
    if current in history:
      loop_length = len( history[history.index(current):] )
      if loop_length == 0:
        print(A[current] + 1)
        return True

      if loop_length == 1:
        print(A[current] + 1)
        return True

      length_to_loop = len( history[:history.index(current)] )
      additional_way = (K-length_to_loop)%loop_length
      print(A[length_to_loop + additional_way] + 1)
      return True

if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
seen = [False]*(N+1)
seen[0] = True
first_seen = [-1]*(N+1)
loop_city = [1]
loop_start = None
cnt = 1
while cnt <= N:
    nxt_city = A[loop_city[-1]-1]
    if seen[nxt_city]:
        loop_num = cnt - first_seen[nxt_city]
        loop_start = first_seen[nxt_city]
        break
    else:
        seen[nxt_city] = True
        first_seen[nxt_city] = cnt # cnt回目の移動で到着した
    loop_city.append(nxt_city)

    if cnt == K:
        print(loop_city[K-1]) # Kが小さい時はこれでいい
        exit()
    cnt += 1


idx = loop_start + (K - loop_start)%loop_num
# print('loop_city',loop_city)
# print('loop_start',loop_start)
# print('loop_num',loop_num)
# print('idx',idx)
# print('ans',A[idx])
print(A[idx])

Submission status: Wrong Answer

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

initcount = 0
count = 0
cur = 0
for _ in range(N):
    count += 1
    T[cur] = True
    cur = A[cur]
    if T[cur]:
        break
initcur = 0
for _ in range(count+1):
    initcount += 1
    initcur = A[initcur]
    if initcur == cur:
        break
if count != initcount:
    count -= initcount

if K <= initcount:
    cur = 0
    for _ in range(K):
        cur = A[cur]
    print(cur+1)
    print("aa")
else:
    K -= initcount
    count = K%count
    for _ in range(count):
        cur = A[cur]
    print(cur+1)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as d 

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

s = '1'
i = 1
while True:
	if str(arr[i - 1]) in s:
		s += str(arr[i - 1])
		break
	s += str(arr[i - 1])
	i = arr[i - 1]

if k <= s.index(s[-1]):
	print(s[k])
else:
	k -= (s.index(s[-1]))
	x = len(s) - s.index(s[-1]) - 1
	print(s[s.index(s[-1]):-1][k%x])

Submission status: Wrong Answer

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

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

count = [0]
Check = [0] * N
while True:
    count.append(A[count[-1]]-1)
    if(Check[count[-1] == 1]):
        break

    Check[count[-1]] += 1
#    print(countCheck, count)

#print(count)


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

loop_kazu = len(count) - saisyo

#print(loop_kazu)
K_loop = K - saisyo

ans_index = K_loop % loop_kazu
#print(ans_index)

ans = count[saisyo + ans_index] + 1

print(ans)

#hoge = count[loop:loop_kaisuu]
#ans = hoge[(K - loop) % loop_kaisuu]

#ans = count[K % loop] + 1

#print(ans)

Submission status: Wrong Answer

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

loopcount=0
tmpPoint=1
vis={1:0}
for i in range(N):
    Next=A[tmpPoint-1]
    if Next in vis:
        startat=i+1
        #print(startat)
        #print(tmpPoint)
        #print(vis)
        #print(Next)
        #print(vis[Next]+1)
        loopcount=i - vis[Next]+1
        break
    vis[Next]=i+1
    tmpPoint=Next

if loopcount==0:
    print(tmpPoint)
    exit()

nokori=(K-startat) % loopcount

#print(startat)
#print(nokori)
#print(loopcount)

tmpPoint=1
for i in range(startat+nokori):
    Next=A[tmpPoint-1]
    tmpPoint=Next
print(tmpPoint)

Submission status: Wrong Answer

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

L = [[0]*2 for i in range(N)]
here = 1
start = -1
startT = -1
end = -1
endT = -1
repeat = -1
count = -1
town = -1

for i in range(N):
    if L[A[here-1]-1][0] == 0:
        L[A[here-1]-1][0] = 1
        L[A[here-1]-1][1] = i
        here = A[here-1]

    else:
        start = L[A[here-1]-1][1] + 1
        startT = here
        end = i
        break


count = (K - start + 1) % (end - start + 1)

if count == 0:
    count = end - start + 1


for i in range(count+1):
    if L[A[here-1]-1][1] != start + count - 2:
        here = A[here-1]
    else:
        town = A[here-1]

print(town)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    a = tuple(map(int, input().split()))
    l = []
    t = 1
    for i in range(n):
        l.append(t)
        k -= 1
        if a[t - 1] in l:
            break
        t = a[t - 1]
    i = l.index(a[t - 1])
    k = k % (len(l)-i)
    print(l[k+i])
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**5)
n, k = map(int, input().split())
A = list(map(int, input().split()))
A = [-1] + A
memo = [1]
def func(i, town=1):
    global memo
    arrival = A[town]
    memo.append(arrival)
    if memo.count(arrival) == 2:
        return memo
    return func(i+1, A[town])

table = func(0, 1)
index = table.index(table[-1])
r = (k - index) % (len(table)-1 - index)
print(table[index+r])

Submission status: Wrong Answer

Solution code:
n, k =[int(i) for i in input().strip().split()]
link = [0] + [int(i) for i in input().strip().split()]
his = [1]
p = link[1]

while True:
    k -= 1
    if p in his:
        break
    his.append(p)
    p = link[p]
    
cycle = his[his.index(p):]
mod = k % (len(cycle))
print(cycle[mod])

Submission status: Wrong Answer

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

edge=[0]*n

for i in range(n):
    edge[i]=a[i]

now=1
to=0
t=k
l=[0]*n
cnt=1
while t!=0:
    to=edge[now-1]
    t-=1
    if l[to-1]!=0:
        break
    else:
        l[to-1]=cnt
        cnt+=1
    now=to

if t==0:
    print(to)
else:
    print(l.index((k-l[to-1]+1)%(max(l)-l[to-1]+1)+l[to-1]-1)+1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
x = [1]
y = set()
y.add(1)
index = 0
for i in range(n):
    next_index = a[index]
    x.append(next_index)
    y.add(next_index)
    index = next_index - 1
    if len(x) != len(y):
        second = i
        target = next_index
        break
index = 0
for i in range(n):
    next_index = a[index]
    index = next_index - 1
    if next_index == target:
        first = i
        break

num = second - first
if num == 0:
    first = -1
    num = second - first

k -= (first + 1)
k %= (second - first)
print(x[first+1+k])