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 itertools

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

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

Loop=1
Next=1

found=[0]*N
while(True):
    found[Next-1]=1
    Next=A[Next-1]
    if(found[Next-1]==1):
        break
    Loop+=1

K=K%(Loop+1)

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

print(Next)

Submission status: Wrong Answer

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

ans = deque()
ans.appendleft(1)
count = 1
s = -1

while True:
    if a[count-1] in a[:count-1]:
        s = a[count-1]
        ans = a[:count-1]
        break
    else:
        count = a[count-1]

if s == -1:
    print(ans[k-1])
else:
    t = ans.index(s)
    if t >= k:
        print(ans[k-1])
    else:
        ans = ans[t:]
        print(ans[(k-t)%len(ans)])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(input().split())
place=1
b=[1]
while place!=0:
 p=place-1
 place=int(a[p])
 b.append(place)
 a[p]=0
c=(len(b)-1)-(b.index(b[-2]))-1 #cが周期を表す
d=b.index(b[-2])
if c==1:
 print(b[-2])
 exit()
elif (k-d)//c>=1:
 r=(k-d)%c
 ans=b[d+r]
else:
 r=k%c
 ans=b[r]
print(ans)

Submission status: Wrong Answer

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

    path = [1]
    next_index = 0
    loop_index = 0
    while True:
        if A[next_index] in path:
            loop_index = path.index(A[next_index])
            break
        else:
            path.append(A[next_index])
            next_index = A[next_index] - 1

    first_A = path[:loop_index]
    loop_A = path[loop_index:]

    if K < len(first_A):
        ans = path[K-1]
    else:
        _, m = divmod(K - len(first_A), len(loop_A))
        ans = loop_A[m]

    return ans


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

Submission status: Wrong Answer

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

if k<=n:
 for i in range(0,n):
  x=a[x]
 print(x)

else:

 for i in range(0,n):
  x=0
  x=a[x]
 for j in range(0,i-1):
  y=a[y]
  if x==y:
   break
  else:
   y=x
  
 w=y+k%(x-y+1)
 for l in range(w):
  u=0
  u=a[u]
 print(u)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
tele = []
here = 1
for i in range(k+1):
    here = a[here-1]
    if a[here-1] in tele:
        break
    tele.append(a[here-1])

if i == k + 1:
    print(tele[-1])
    exit()

K = (k - tele.index(a[here-1])) % (len(tele) - tele.index(a[here-1]))
if K == 0:
    print(tele[-1])
else:
    print(tele[K + tele.index(a[here-1]) - 2])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
towns = list(map(int, input().split()))
place_count = [0] * (n + 1)
next_place = 1
teleport_count = 0
for i in range(n * 2):
  place_count[next_place] += 1
  next_place = towns[next_place - 1]
one_move_place = place_count.count(1)
for place in place_count:
  if place > 1:
    teleport_count += 1
next_place = 1
for _ in range(one_move_place + k % teleport_count):
  next_place = towns[next_place - 1]
print(next_place)

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())
ai = list(input().split())
i = (k%n)-1
a=int(ai[i])-1
print(ai[a])

Submission status: Wrong Answer

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

now = 1
next = a_list[now-1]

while True:
    if now in route:
        start = route.index(now)
        end = len(route)
        junkai = route[start:end]
        amari = route[:start]
        break
    route.append(now)
    now = next
    next = a_list[now-1]
    
hoge = (k-len(amari))%len(junkai)
print(junkai[hoge])

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
def tele(i):
    ans = A[i-1]
    return ans
i = tele(1)
if N >= K:
    for j in range(K-1):
        i = tele(i)
        print(i)
else:
    l = [i]
    for j in range(N-1):
        i = tele(i)
        if i not in l:
            l.append(i)
    else:
        a = l.index(i)
        loop = len(l) - a
        ans = (K - a) % loop
        q = l[ans -1]
    print(q)

Submission status: Wrong Answer

Solution code:
def calc(i):
    ans_list = [i]
    ans_set = set([i])
    count = 1
    i = a[i]
    while (i not in ans_set) & (count <= n):
        ans_list.append(i)
        ans_set.add(i)
        count += 1
        i = a[i]
    index = ans_list.index(i)
    ans_list.append(i)
    return count, ans_list

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

count, ans_list = calc(0)
if count <= n:
    index = ans_list.index(ans_list[-1])
    k = k - index
    ans_list = ans_list[index + 1:]
    print(ans_list[k % len(ans_list) - 1] + 1)
else:
    index = ans_list[-1]
    ans_list = ans_list[index:]
    k = k - index
    k = k % len(ans_list)
    print(ans_list[k] + 1)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
A = list(map(int, input().split()))

# ループ解析
step_on = [-1] * N
current = 1
min_mv_count = 0
i = 0
#for i in range(N + 1):
looped = False
while(not looped):
    #print(current)
    if step_on[current - 1] == -1:
        step_on[current - 1] = i
        current = A[current - 1]
        i += 1
    else:
        #print("else")
        looped = True
        period = i - step_on[current - 1]
        pre_mv = i - period
        min_mv_count = pre_mv + ((K - pre_mv) % period)
        #print("period {} pre_mv {}".format(period, pre_mv))
        #print("min_mv_count {}".format(min_mv_count))
        break

current = 1
#for i in range(K + 1): # 正攻法
for i in range(min_mv_count):
    current = A[current - 1]
print(current)

Submission status: Wrong Answer

Solution code:
def F(k):
    ans = 1
    for _ in range(k): ans = A[ans-1]
    return ans

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

dp = [0]*n
if A[0] == 1: exit(print(1))

p = A[0]-1
dp[0]+=1
count = 1
stop = False
while True:
    if p == A[p]-1:
        stop = True
        break
    p = A[p]-1
    if dp[p] > 0:
        count += 1
        break
    count += 1
    dp[p]+=count
dp[0]=0
if (stop and k >= count) or k == count: exit(print(p+1))
if k > count: k = k % (count-dp[p])
print(F(k))

Submission status: Wrong Answer

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

A = list(map(int,input().split()))
B = [1]
ex = 1

for i in range(N):
    ex = A[ex - 1]
    if ex in B:
            p = B.index(ex)
            r = ex
            Z = (K - p) % (i + 1 - p)
            break
    else:
            B.append(ex)

ans = ex
for k in range(Z):
    ans = A[ans - 1]
    k = k + 1
    
    
print(ans)

Submission status: Wrong Answer

Solution code:
def mips():
    return map(int,input().split())
def msps():
    return map(str,input().split())

import sys
import itertools
N,K = mips()
A = [el for el in mips()]
Seen = [[] for _ in range(0,N+1)]
x = 1
t = 0
for _ in range(100):
    x = A[x-1]
    t += 1
    Seen[x].append(t)
l = len(Seen)
for i in range(l):
    if Seen[i] != []:
        if (Seen[i][0] % 3 == K%3):
            print(i)
            sys.exit(0)

Submission status: Wrong Answer

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

for j in range(2*N):
    i = A[i-1]
    if i in B:
        I = A[i-1]
        break
    else:
        B.append(i)
        
count = 0
i = 1
for j in range(2*N):
    if I == A[i-1]:
        CT = count
        break
    else:
        count += 1
        i = A[i-1]
        
flag = True
i = I
C = [I]

for j in range(2*N):
    if A[i-1] == I:
        break
    else:
        i = A[i-1]
        C.append(i)

if K >= CT:
    D = C[(K-CT-1)%(len(C))]
    print(str(D))
else:
    print(str(B[K]))

Submission status: Wrong Answer

Solution code:
import sys
N, K = map(int, input().split()) #N: 町の数, K: ちょうどこの回数でたどり着く町

visited = [False for _ in range(N)]

A = list(map(int, input().split()))
tmp = 0 #次に訪れる番号
visited[0] = True
cnt = 0 #テレポートの回数
log = [0] #テレポートの記録

while True:
    tmp = A[tmp] - 1
    if cnt == K:
        print(tmp)
        sys.exit()
    if visited[tmp]: #一度訪れたことがあった場合
        start = log.index(tmp)
        break

    visited[tmp] = True
    log.append(tmp)
    cnt += 1

roop = log[start:cnt+1]
period = len(roop)

remain = K - cnt-1

print(roop[remain%period] + 1)

Submission status: Wrong Answer

Solution code:

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

#ループする場合
flag=[0]*N
patt=[]
aaaa=0
i=0
while True:
    patt.append(i)
    if flag[i]==1:
        #del patt[-1]
        break
    flag[i]=1
    i=A[i]-1


srt = patt.index(patt[-1])
#print('srt',srt)
end = len(patt)-2
ptrn = patt[srt:end+1]

if K<len(ptrn):
    print(patt[K])
else:
    B = (K-srt) % len(ptrn)
    #print('B',B)

    print(ptrn[B]+1)
    #print('0000000')

    #print('ptrm',ptrn)
    #print(patt)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
lst = list(map(int, input().split()))
ans = []
dict = {}
at = 1
amari = 0
loop = 0
dict[1] = 1

while 1 :
    at = lst[at - 1]
    if at in dict.keys() :
        dict[at] += 1
    else :
        dict[at] = 1
    if max(dict.values()) == 1:
        amari += 1
    if max(dict.values()) == 2:
        ans += [at]
        loop += 1
    if max(dict.values()) == 3:
        break

value = (k + 1 - amari) % loop
print(lst[value])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
visited = [False for _ in range(n)]
nx = A[0] - 1
x = []
p = -1
for e, i in enumerate(range(n)):
    if visited[nx] == False:
        visited[nx] = True
        x.append(nx)
        nx = A[nx] - 1
    else:
        p = x.index(nx)
        q = x[:p]
        r = x[p:]
        break
if p!=-1:
    k = (k-len(q))%len(r)
    print(r[k-1]+1)
else:
    print(x[k-1])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
c=2
t=0
path=[]
s=set()
cy=[]
while c<=k:
    if a[t] in s:
        cy=path[path.index(a[t]):]
        k=c-1
        break
    path.append(a[t])
    s.add(a[t])
    t=a[t]-1
    c+=1
if cy==[]:
    print(a[t])
else:
    print(cy[k%len(cy)])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(500000)

N, K = map(int, input().split())
dist = [[] for i in range(N)]
A = list(map(int, input().split()))
for i in range(N):
    dist[i].append(A[i] - 1)
dp = [[0, 0] for i in range(N)]

def dfs(pos, depth):
    if dp[pos][0] != 0 and dp[pos][1] != 0:
        return
    # 初めての訪問なら
    if dp[pos][0] == 0:
        dp[pos][0] = depth
        for i in dist[pos]:
            dfs(i, depth + 1)
    elif dp[pos][1] == 0:
        dp[pos][1] = depth
        for i in dist[pos]:
            dfs(i, depth + 1)
dfs(0, 0)
for i in range(N):
    if dp[i][0] != 0:
        if dp[i][0] == K or dp[i][1] == K:
            print(i + 1)
            break
        else:
            split = dp[i][1] - dp[i][0]
            if split > 0:
                if (K - dp[i][0]) % split == 0:
                    print(i + 1)
                    break

Submission status: Wrong Answer

Solution code:
def main():
    from builtins import int, map, list, print, len
    import sys
    sys.setrecursionlimit(10 ** 6)

    input = sys.stdin.readline
    input_list = (lambda: input().rstrip().split())
    input_number = (lambda: int(input()))
    input_number_list = (lambda: list(map(int, input_list())))

    N,K= input_number_list()
    A = input_number_list()
    route = [1]
    now = 1
    is_looop = False
    try:
        for i in range(N):
            if A[now-1] in route:
                is_looop = True
                break
            now = A[now-1]
            route.append(now)
    except Exception as e:
        pass
    if is_looop:
        start = A[now-1]
        start_idx = route.index(start)
        l_count = start_idx
        r_count = len(route) - start_idx
        K -= l_count
        m = K % r_count
        print(route[start_idx + m])
    else:
        print(route[K-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
a = list(map(int, input().split()))
roop = [0]
start = 0
index = 0
fin = False
while True:
    if a[index] - 1 in roop:
        start = roop.index(a[index] - 1)
        break
    else:
        roop.append(a[index] - 1)
        index = a[index] - 1
        if len(roop) == K + 1:
            print(index)
            fin = True
if fin == False:  # len(roop)<=K
    if (K + 1 - start) % len(roop[start:]) == 0:
        print(roop[-1] + 1)
    else:
        print(roop[start + (K + 1 - start) % len(roop[start:]) - 1] + 1)

Submission status: Wrong Answer

Solution code:
def main():
	n, k = [int(x) for x in input().split(" ")]
	a = [int(x) for x in input().split(" ")]
	d = {}
	pos = 0
	step = 0
	cycle = False
	way = []
	while step < k and cycle == False:
		if pos in d:
			cycle = True
			step += 1
		else:
			d[pos] = step
			way.append(a[pos])
			pos = a[pos] - 1
			step += 1

	k -= step
	if k > 0:
		cycle = way[d[pos]:step]
		x = k % len(cycle)
		print(cycle[x])
	else:
		print(a[pos])

main()

Submission status: Wrong Answer

Solution code:
input_line = input().split()
n = int(input_line[0])
k = int(input_line[1])
input_line = input().split()
towns = [int(town) for town in input_line if int(town) != input_line.index(town) + 1]

num = k % len(towns)
now = 1
for i in range(num):
    now = int(input_line[now - 1])

print(now)

Submission status: Wrong Answer

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


now = 1
repeat = list()


while now not in repeat:
    repeat.append(now)
    now = a[now-1]


repeat = repeat[repeat.index(now):]
print(repeat)


k = k % (len(repeat))


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


print(now)

Submission status: Wrong Answer

Solution code:
def cal():

    n, times = input().split(" ")
    n = int(n)
    times = int(times)
    towns = list(map(int, input().split()))
    position = [1]
    t = 0
    while 1:
        if towns[t] in position:
            break
        else:
            position.append(towns[t])
            t = towns[t] - 1
    p = position.index(towns[t])
    c = len(position) - p
    ans = (times + 1 - p) % c
    newPosition = position[p:]
    key = newPosition[ans - 1]
    print(key)
    # print(position)
    # print(newPosition)
    # print(ans)
    # print(p)
    # print(c)

cal()

Submission status: Wrong Answer

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

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

temp =1

road=[1]

while len(road) < N*2:
    temp =  A[temp-1]
    road.append(temp)
    
print(road[N-1])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
b=[1]
t=0
for i in range(n):
    for j in range(len(b)):
        if b[j]==a[b[i]-1]:
            r=j
            t=1
            break
    if t==1:
        break
    b.append(a[b[i]-1])
b1=b[:r]
b2=b[r:]
print(b1)
print(b2)
print(r)
if k<=r:
    print(b1[k-1])
else:
    print(b2[((k-r)%len(b2)+len(b2))%len(b2)])

Submission status: Wrong Answer

Solution code:
import sys

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

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

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

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


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

if a[0]==0:
    print("1")
else:
    print(otozure[i-1+nokori]+1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = []
cur = 0
for _ in range(n):
    if a[cur] in d:
        break
    d.append(a[cur])
    cur = a[cur] - 1
st = d.index(a[cur])
hyo = len(d) - st
amari = (k-st)%hyo
print(d[amari+st-1])

Submission status: Wrong Answer

Solution code:
import numpy as np
import math
import scipy as sp
import queue
import collections

MOD = 10 ** 9 + 7
INF = 10 ** 9

def main(kwargs):
    n = kwargs["n"]
    k = kwargs["k"]
    A = kwargs["A"]
    now = 0
    cnt = 1
    R = [0 for i in range(n)]
    R[0] = cnt

    while True:
        now = A[now] - 1
        cnt += 1

        if R[now] > 0:
            cnt = R[now] + k // (cnt - R[now]) * (cnt - R[now])

        R[now] = cnt

        if cnt > k:
            break

    res = now + 1

    return res

if __name__ == "__main__":
    kwargs = {}

    cin = input().split()
    kwargs["n"], kwargs["k"] = [int(i) for i in cin]

    cin = input().split()
    kwargs["A"] = [int(i) for i in cin]

    cout = main(kwargs)
    print(cout)

Submission status: Wrong Answer

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

i=1
ans=[]
while x[i-1] not in ans:
    ans.append(x[i-1])
    i=x[i-1]
ans.append(x[i-1])
cor=ans[ans.index(ans[-1]):-1]


yeah=k%len(cor)
print(x[yeah])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
B=[0]
ind=0
while A[ind]-1 not in B:
    B.append(A[ind]-1)
    ind=A[ind]-1
B.append(A[ind]-1)
b_dup=B.index(B[-1])
long=len(B)-b_dup-1
print(A[B[(k-b_dup)%long+b_dup-1]])

Submission status: Wrong Answer

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

now = 1
loop_node = []
first_loop = 0
l = [0 for _ in range(N)]
while True:
    l[now - 1] += 1
    if l[now - 1] == 3:
        break

    if l[now - 1] == 2:
        loop_node.append(now)

    now = A[now - 1]
    first_loop += 1
loop_num = len(loop_node)

print(loop_node[((K + 1) - (first_loop - loop_num * 2)) % loop_num])

Submission status: Wrong Answer

Solution code:
def main():
    
    IN = [int(_) for _ in input().split()]
    A = [int(_) for _ in input().split()]
    N = IN[0]
    K = IN[1]

    loop = []
    target = 1
    mark = [False] * N
    mark[0] = True
    while True:
        target = A[target -1]
        loop.append(target)
        if mark[target-1]:
            break
        mark[target-1] = True 

    looper = loop
    si = len(loop)-1
    if loop[si] != 1:
        K = K - loop[si] -1
        looper = loop[loop[si]-1:si]

    ind = (len(looper) % K) - 1
    print(A[ind])
        



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def solve():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    b_lst = [False] * N
    b_lst[0] = True
    ans = 1
    save = -1
    counnnt = 0
    while True:
        counnnt += 1
        ans = A[ans-1]
        if b_lst[ans - 1]:
            break
        else:
            b_lst[ans-1] = True
    counter = 0
    save = ans
    while True:
        counter += 1
        ans = A[ans-1]
        if ans == save:
            break
    K = K-(counnnt-counter)
    if K < 0:
        ans = 1
        for i in range(K):
            ans = A[ans-1]
        print(ans)
        sys.exit(0)
    K %= counter
    for i in range(K):
        ans = A[ans-1]
    print(ans)


solve()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline


def readstr():
    return input().strip()


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    A = list(readnums())
    '''
    setでinを回したい
    -> l = set()
    順序も保持したい
    dictで保持？
    {1: 0, 3: 1, 4: 2, 1: 3, ...}
    a in l = Trueのとき
    dict[a]
    '''
    l = {A[0]}
    dic = {A[0]: 0}
    a = A[0]
    for i in range(1, N):
        a = A[a - 1]
        if a in l:
            d = dic[a]
            loop = list(dic.keys())[d:]
            print(loop)
            K -= d
            print(loop[K % len(loop) - 1])
            break
        else:
            l.add(a)
            dic[a] = i
    else:
        print(list(dic.keys())[-1])


if __name__ == "__main__":
    main()

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(2 * N + 1):
  #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
input = sys.stdin.readline

def main():
    N, K = map(int, input().split())
    A = [int(v) for v in input().split()]
    i = 0
    p = 1
    memo = [0] * N
    loop = 0
    for i in range(K):
        p = A[p - 1]
        if memo[p - 1] == 0:
            memo[p - 1] = i
        else:
            loop = memo[p - 1] - i
            break
    
    if i < K:
        print(p)
    else:
        s = (K-i+1)%loop
        for i in range(s, K):
            p = A[p - 1]
        print(p)
    


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
visited = []
ans = 0
now = 0
lim = 2 * 10**5 + 1
while not now in visited and ans <= lim:
    visited.append(now)
    now = a[visited[-1]]-1
    ans += 1
visited.append(now)

ln1 = len(visited)-1
idx = visited.index(now)
ln2 = len(visited[idx:-1])
ln = (k-ln1)%ln2

print(visited[idx+ln]+1)

Submission status: Wrong Answer

Solution code:
from sys import stdin
N,K = [int(x) for x in stdin.readline().rstrip().split()]
A = [int(x) for x in stdin.readline().rstrip().split()]

visited = [False]*(N+1)
visited[1] = True

tmp = [0]*(N+1)
cnt = 1
zyunkai = 0
idou = A[0]
tmp[idou] = 1
A = [0] + A
ans = [0]*(N+1)
ans[1] = A[1]

cook = 0
for i in range(N+1):
   
    cnt += 1
    ans[cnt] = A[idou]
    idou = A[idou]
    if visited[idou]:
        zyunkai = cnt - tmp[idou]
        cook = tmp[idou]
        K -= tmp[idou]
        break
    tmp[idou] = cnt
    visited[idou] = True

ooo = K%zyunkai
#print(zyunkai,cook)
ans = ans[ooo+cook]
print(ans)

Submission status: Wrong Answer

Solution code:
# /usr/bin/python3
# -*- coding: utf-8 -*-
from queue import Queue
from queue import LifoQueue as Stack
from math import sqrt, floor, ceil, log2, log10, pi
from fractions import gcd
from itertools import permutations, combinations
from operator import itemgetter
from functools import cmp_to_key


INF=1001001001
__MOD__=(10**9)+7
yn = 'YNeos'
judge = False
cnt = 0
ans = None


def lcm(a, b):
    return (a*b) // gcd(a,b)

def intinput():
    return int(input())

def mulinputs():
    return map(int,input().split())

def lineinputs(func=intinput):
    datas = []
    while True:
        try:
            datas.append(func())
        except EOFError:
            break
    return datas

class ModInt():
    def __init__(self, x):
        self.__x = (x % __MOD__)
    def __add__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x + other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x + other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __radd__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x + self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x + self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __sub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x - other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x - other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rsub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x - self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x - self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __mul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rmul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __truediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rtruediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __pow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(self.__x, other.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(self.__x, other.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")
    def __rpow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(other.__x, self.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(other.__x, self.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")

    def __modinv(self, m=__MOD__):
        a = self.__x
        if a == 0:
            raise ZeroDivisionError()
        if gcd(a, m) != 1:
            raise Exception("%sの逆数は求まりません。" % a)
        b, u, v = m, 1, 0
        while b != 0:
            t = a//b;
            a -= t*b
            a, b = b, a
            u -= t * v
            u, v = v, u
        u %= m
        if u < 0:
            u += m
        return u
    def __int__(self):
        return self.__x
    def __str__(self):
        return str(self.__x)



if __name__ == '__main__':
    N, K = mulinputs()
    datas = list(mulinputs())

    # idx = 0
    # next = 1
    # dones = [False] * N
    # dones[0] = True
    # while idx < K:
    #     if dones[next-1]:
    #         break
    #     dones[next-1] = True
    #     next = datas[next-1]
    #     idx += 1
    # loop_cnt = idx + 1
    idx = 0
    next = 1
    dones = [0] * N
    while idx < N*2:
        dones[next-1] += 1
        next = datas[next-1]
        idx += 1
    mono_cnt = len(list(filter(lambda x: x == 1, dones)))
    if K <= mono_cnt:
        idx = 0
        next = 1
        while idx < K-1:
            next = datas[next-1]
            idx += 1
        print(next)
        exit()

    loop_cnt = len(list(filter(lambda x: x > 1, dones)))
    loop = []
    # for idx, elm in enumerate(datas):
    #     print(idx, elm)
    #     if dones[idx] <= 1:
    #         continue
    #     loop.append(elm)
    idx = 0
    next = 1
    _cnt = 0
    while idx < N:
        if dones[next-1] > 1:
            if _cnt < loop_cnt:
                loop.append(datas[next-1])
                _cnt += 1
        next = datas[next-1]
        idx += 1

    idx = ((K-mono_cnt)%loop_cnt) - 1
    if idx < 0:
        idx = loop_cnt - 1
    # print("mono: {}, loop_cnt: {}, idx: {}, loop: {}".format(mono_cnt, loop_cnt, idx, loop))
    print(loop[idx])
    # _k = int(K - (K // loop_cnt) * loop_cnt)
    # idx = 0
    # next = 1
    # while idx < _k:
    #     next = datas[next-1]
    #     idx += 1

    # # 出力
    # print(next)