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

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

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

		if x==y:
			return

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

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

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

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

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

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

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

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

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

first = ex_r.index(ex_r[-1])
ex_r.pop()
repeat = len(ex_r)-first


if first>=k:
	print(ex_r[k])
else:
	first = max(first,1)
	amari = (k-(first-1))%repeat
	print(ex_r[first+amari-1])

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

N,K=list(map(int,input().split()))
a_list=list(map(int,input().split()))
alr = defaultdict(int)
alr[1] = 1
counter = 2
next = a_list[0]
base_roop = 0
last_index = 1
while True:
    if alr[next] != 0:
        base_roop = counter-1
        break
    else:
        alr[next] = counter
        last_index = next
        next = a_list[next-1]
        counter += 1

# nextから何回でlastに帰ってくるか
alr_next = defaultdict(int)
next_roop = 0
while True:
    if a_list[next-1]==last_index:
        next_roop += 1
        alr_next[next] = next_roop
        break
    else:
        next_roop+=1
        alr_next[next] = next_roop
        next = a_list[next-1]
next_roop+=1

if K<=base_roop:
    ans = K%base_roop+1
    for k,v in alr.items():
        if v==ans:
            print(k)
            exit()
else:
    K-=base_roop
    ans = K%next_roop+1
    for k,v in alr_next.items():
        if v==ans:
            print(k)
            exit()
    print(last_index)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
a=[0]*n
a[0]=1
nxt=A[0]-1
i=2
while 1:
  a[nxt]=i
  nxt=A[nxt]-1
  i+=1
  if a[nxt]!=0:
    g=i-a[nxt]
    t=a[nxt]-1
    break
if g>=k+1:
  print(a.index(k+1))
else:
  k-=t
  u=k%g
  print(a.index(t+u+1)+1)

Submission status: Wrong Answer

Solution code:
import sys
N,K = map(int,input().split())
tele = list(map(int,input().split()))
k = 1
goal = tele[0]
miti = [1]
while (goal in miti)!=1:
    k += 1
    miti.append(goal)
    goal = tele[goal-1]
    if k == K:
        goal = tele[goal-1]
        print(goal)
        sys.exit()

a = miti.index(goal)
loop = k-a
ans = miti[(K-a)%loop+a]

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
reach = [1]
loopEnd = 1
target = 1
while(True):
    if a[target - 1] in reach:
        target = a[target - 1]
        break
    reach.append(a[target - 1])
    loopEnd = loopEnd + 1
    target = a[target - 1]
loopStart = reach.index(target)
loop = loopEnd - loopStart
if k <= loopStart:
    print(reach[k - 1])
else:
    print(reach[loopStart + (k - loopStart) % loop])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")

#solve
def solve():
    n, k = LI()
    a = LI_()
    d = defaultdict(int)
    i = a[0]
    t = 1
    d[0] = 1
    while not d[i]:
        t += 1
        d[i] = t
        i = a[i]
    if n >= k:
        i = 0
        for _ in range(k):
            i = d[i]
        print(i + 1)
    else:
        k -= d[i] - 1
        k %= (t - (d[i] - 1))
        for _ in range(k):
            i = a[i]
        print(i + 1)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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

town = 0
visited = [town]
index = 0
visited_index = {town: index}
loop = None
while K > 0:
    K -= 1
    town = A[town]
    if town in visited_index:
        loop = visited[visited_index[town]:]
        break
    visited.append(town)
    index += 1
    visited_index = {index: town}

if loop:
    K %= len(loop)
    print(loop[K]+1)
else:
    print(town+1)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

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

# ループを見るける
target = deque()
target_s = set()
target.append(1)
target_n = A[0]
for i in range(K):
    before = len(target_s)
    target_s.add(target_n)
    if len(target_s) != before:
        target.append(target_n)
        # target_s.add(target_n)
        target_n = A[target_n-1]
    else:
        if target[-1] != 1:
            target.append(target_n)
        t = target.pop()
        t = target.index(t)
        K = K%(len(target) - t)
        print(target[K])
        sys.exit()

print(target[-1])

Submission status: Wrong Answer

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

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

now=1
count=0
while count>=0:
  now=where[now-1]
  count=count+1
  print("sss")
  if(now==1):
    break
k=k%count


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

print(now)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
a=list(map(int,input().split()))
cycle=[0]
flag=0
id=0
for i in range(N):
    a[i]-=1
while N>0:
    if a[id] in cycle:
        node=cycle.index(a[id])
        break
    else:
        cycle.append(a[id])
        id=a[id]
    N-=1
K-=node
cycle=cycle[node::]
q=K%len(cycle)
print(cycle[q]+1)

Submission status: Wrong Answer

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

t=a[0]
d=[]
d.append(t)
num=k-1
s=0
for i in range(k-1):
    t=a[t-1]
    if(t in d):
        s=d.index(t)
        num-=1
        break
    d.append(t)
    num-=1

print(d[num%len(d)-s])

Submission status: Wrong Answer

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

A = list(map(int,input().split()))
t = 0
c = 0
ans = [0] * n
L = []
s = 0
for _ in range(k):
    if ans[t] == 1:
        n = len(L) - L.index(t)
        temp = t + k%n
        temp %= n
        t = L[L.index(t):][temp]
        break
    else:
        ans[t] = 1
        L.append(t)
        t = A[t]-1
        c += 1
print(t+1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
time = 0
roop = [1]
while(len(set(roop)) == len(roop)):
    roop.append(a[roop[-1]-1])
first = roop.index(roop[-1])
roop.pop(-1)
if(first != 0):
    atama = len(roop) - first
    print(atama)
    gachiroop = roop[atama-1:]
    print(gachiroop[(k-atama+1)%len(gachiroop)])
else:
    print(roop[k%len(roop)])

Submission status: Wrong Answer

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

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

print(togo+1)

Submission status: Wrong Answer

Solution code:
data = input().split()
n = int(data[0])
k = int(data[1])
t = list(map(int,input().split()))

p = t[0]
loop = []
while True:
    loop.append(p)
    p = t[p-1]
    if p in loop:
        repeat = p
        r_point = loop.index(p)
        break
#print(loop)
once = loop[:r_point]
repeat = loop[r_point:]
#print(once,repeat)

k -= len(once)
amari = k%len(repeat)
print(repeat[amari-1])


#6 727202214173249351
#6 5 2 5 3 2

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
s=1
sa=set()
d=dict()
count=0
niko=0
anss=0
bx=False
while True:
  count+=1
  if count+1==k:
    anss=a[s]
    bx=True
    print(a[s])
    count-1
    break
  if not (a[s-1] in sa):
    sa.add(a[s-1])
    d[a[s-1]]=count
    s=a[s-1]
  else:
    niko=a[s-1]
    number=count-d[a[s-1]]
    break
if bx==False:
  lf=False
  ans_list=[]
  kaisu=0
  for i,j in d.items():
    if i==niko:
      lf=True
      kaisu=j
    if lf==True:
      ans_list.append(i)
  print(ans_list[(k-kaisu)%number])

Submission status: Wrong Answer

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

#足跡
footprint=[0]*n

omoide=[]
now=0
counter=1
while True:
    if footprint[now]!=0:
        break
    footprint[now]=counter
    omoide.append(now)
    goto=alist[now]-1
    now=goto
    counter+=1

joso=footprint[now]-1
shuki=counter-footprint[now]

k-=joso
k=k%shuki

ans=omoide[joso+k]+1

print(ans)

Submission status: Wrong Answer

Solution code:
n , k = map(int, input().split())
a = list(map(int,input().split()))
v = [0]*(n+1)
v[1]=1
v2=[1]
i=0
step=1

while True:
    if v[a[i]]!=0:
        loop=step-v[a[i]]+1
        loopstart=v[a[i]]
        break
    else:
        step+=1
        v[a[i]]=step
        v2.append(a[i])
        i=a[i]-1
ans = (k-loopstart+2)%loop
if ans ==0:
    ans+=loop
if k<loopstart:
    print(v2[k-1])
v2=v2[loopstart-1:]
print(v2[ans-1])

Submission status: Wrong Answer

Solution code:
import sys
import os
import math
import bisect
import collections
import itertools
import heapq

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    A = il()
    t = []
    tmp = 1
    while True:
        if tmp in t:
            break
        t.append(tmp)
        tmp = A[tmp - 1]
    D, M = divmod(K, len(t)-t.index(tmp))
    print(t[M])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

tmp = 1
num = []

for i in range(N):
    num.append(tmp)
    tmp = A[tmp-1]
    if tmp in num :
        judge = tmp
        break

print(num[(K-num.index(judge))%(len(num)-num.index(judge)) + num.index(judge)])

Submission status: Wrong Answer

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

n = 1
rooper = -1
L = []
for i in range( K ):
  n = A[ n - 1 ]
  if n in L:
    rooper = n
    break
  else:
    L.append( n )
if rooper == -1:
  print( n )
else:
  index = L.index( rooper )
  if len( L ) - index > 0:
    a = ( K - index ) % ( len( L ) - index )
  else:
    a = 0
    print( "attenaiyo" )
  print( L[ index + a - 1 ] )

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
lis = [-1] * len(A)
nex = 1
start = 0
loop = 0
for i in range(len(A)):
    if lis[nex-1] ==-1:
        lis[nex-1]=i
        nex = A[nex-1]
    else :
        start = nex
        loop = i - lis[nex-1]
        break
nex = start
end = (K-lis[start-1])%loop
for i in range(end):
    nex = A[nex-1]

print(nex)

Submission status: Wrong Answer

Solution code:
import sys
import re
import math
import collections
import decimal
import bisect
import itertools
import fractions
import functools
import copy

# import heapq
# from collections import deque
# import decimal

sys.setrecursionlimit(10000001)
INF = sys.maxsize
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===

def main():
    n, k = ns()
    a = na()
    a = [ai - 1 for ai in a]

    junkan_point = 0
    visited = [0, a[0]]
    next = a[0]

    visited_set = set(visited)

    for _ in range(n):
        if a[next] in visited_set:
            flg = True
            junkan_point = a[next]
            break
        else:
            visited.append(a[next])
            visited_set.add(a[next])
            next = a[next]

    tmp_idx = visited.index(junkan_point)
    junkan_visited = visited[tmp_idx:]

    tmp = len(visited) - len(junkan_visited)
    if k <= tmp:
        print(k)
    else:
        idx = (k-tmp) % len(junkan_visited)
        print(tmp+idx+1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
circle=[1]
counter=0
flag=0
while flag==0:
    circle.append(A[circle[counter]-1])
    counter+=1
    if circle[counter]==1:
        flag=1
    elif counter==n:
        flag=1
l=k%counter
print(circle[l])

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
A = [0] + [int(i) for i in input().split()]
B = [1]
while(True):
    tmp = A[B[-1]]
    if not tmp in B:
        B += [tmp]
    else:
        head = B.index(tmp)
        break
K = (K - len(B[:head]))  % len(B[head:])
print(B[head:][K])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
senni=[1]
dabu=False
while dabu == False:
    if a[senni[-1]-1] in senni:
        dabu = True
        t=len(senni)-(senni.index(a[senni[-1]-1]))
        break
    senni.append(a[senni[-1]-1])
if t<=k and k%t < senni.index(a[senni[-1]-1]):
    ans = senni[k%t+t]
else:
    ans=senni[k%t]
print(ans)

Submission status: Wrong Answer

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

s=1
r=[1]
for i in range(n):
  s=l[s-1]
  if s not in r:
    r.append(s)
  else:
    break
x=r.index(s)
mod=len(r)-x
t=(k-i-1)%mod
print(r[x+t])

Submission status: Wrong Answer

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


t=1
track=[]
while not(t in track):
	track+=[t]
	t=a_ls[t-1]

#print(track)
#print(t)
#print(track.index(t)) #dokokara loop ga hajimaruka

if track.index(t)>K:
	print(track[K])
else:
	s=(K+1-track.index(t))%(len(track)-track.index(t))
	print(track[s+track.index(t)-1])

Submission status: Wrong Answer

Solution code:
def find_size(A):
    visited = set()
    visited_index = dict()
    now = 0
    size = 0
    while True:
        if now in visited:
            return visited_index[now], size - visited_index[now]
        visited.add(now)
        visited_index[now] = size
        now = A[now]
        size += 1
    return None

def find_n(A, N):
    now = 0
    for _ in range(N):
        now = A[now]
    return now

int1 = lambda s: int(s)-1

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

start, size = find_size(A)
if K <= start + size:
    print(find_n(A, start + size) + 1)
else:
    print(find_n(A, (start + ((K - start) % size))) + 1)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
X = [1]
pos = 0
for i in range(2 * N):
    X.append(A[pos])
    pos = A[pos] - 1
# rint(X)

s = set()
loop = len(X)
for i, x in enumerate(X):
    if x in s:
        loop = i
        break
    else:
        s.add(x)
#print(loop)
x, y = X[loop], X[loop + 1]
for i in range(N-1):
    if X[i] == x and X[i + 1] == y:
        base = i
        break
# print(base)
diff = loop - base
if K < base:
    print(X[K])
else:
    mod = K % diff
    # print(mod)
    print(A[mod])

Submission status: Wrong Answer

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

a = list(map(int,input().split()))
b = [0 for i in range(2*10**5)]
l = []
x = 0
for i in range(2*10**5):
    if b[x] == 0:
        b[x] += 1
    else:
        res = x+1
        break
    
    l.append(x+1)
    x = a[x]-1




roup = l[l.index(res):]

k -= (len(l)-len(roup))

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

Submission status: Wrong Answer

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

a = list(map(int,input().split()))
# ~print(a)
cycle = []
index = 0
if (1 in a):
	for i in range(len(a)):
		if (a[i] == 1):
			index = i
			break
it = index
for i in range(n):
	# ~if (a[it] in cycle):
		# ~break
	cycle.append(a[it])
	it = a[it]-1
# ~print(cycle)
if (1 in a):
	print(cycle[(k+1)%n])
else:
	print(cycle[(k-1)%n])

Submission status: Wrong Answer

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

d = a[0]
b = [d]

for i in range(k):
    dn = a[d-1]
    if b[0]!=dn:
        d = dn
        b.append(d)
    else:
        break
        

if len(b)<k:
    print(dn)
else:
    print(b[k%len(b)])

Submission status: Wrong Answer

Solution code:
# region header
import sys
import math
from bisect import bisect_left, bisect_right, insort_left, insort_right
from collections import defaultdict, deque, Counter
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from heapq import heappop, heappush
from itertools import accumulate, groupby, product, permutations, combinations, combinations_with_replacement
from math import ceil, floor, factorial, log, sqrt, sin, cos
from operator import itemgetter
from string import ascii_lowercase, ascii_uppercase, digits
sys.setrecursionlimit(10**6)
INF = float('inf')
MOD = 10 ** 9 + 7
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(rs())
def rf(): return float(rs())
def rs_(): return [_ for _ in rs().split()]
def ri_(): return [int(_) for _ in rs().split()]
def rf_(): return [float(_) for _ in rs().split()]
def divisors(n, sortedresult=True):
    div = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            div.append(i)
            if i != n // i:
                div.append(n//i)
    if sortedresult:
        div.sort()
    return div
# endregion
N, K = ri_()
A = ri_()
d = [0] * N
d[0] = 1
cnt = 1
loop = 0
now = 0
while True:
    now = A[now] - 1
    if d[now]:
        loop = cnt - d[now] + 1
        break
    else:
        cnt += 1
        d[now] = cnt
ans = bisect_left(d, (d[now] + (K - d[now]) % loop) % loop + 1) - 1
print(A[ans])

Submission status: Wrong Answer

Solution code:
import sys
N,K = map(int,input().split())
tele = list(map(int,input().split()))
k = 1
goal = tele[0]
miti = [1]
while (goal in miti)!=1:
    k += 1
    miti.append(goal)
    goal = tele[goal-1]
    if k == K:
        goal = tele[goal-1]
        print(goal)
        sys.exit()
print(miti)

a = miti.index(goal)
loop = k-a
ans = miti[(K-a)%loop+a]

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
A = list(map(int, input().split()))
for i in range(N) :
    if A[i] == 1 :
        break
i += 1
print(A[K%i])

Submission status: Wrong Answer

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n,k = readInts()
    A = readInts()
    root = []
    ok = True
    l = 0
    dic = defaultdict(int)
    while True:
        if ok:
            a = 1
            ok = False
        else:
            a = root[-1]
        if dic[A[a-1]] != 2:
            dic[A[a-1]] += 1
            root.append(A[a-1])
        else:
            j = 0
            for i in range(len(root)):
                if A[a-1] == root[i]:
                    j = i
            root = root[j:]
            l = j
            #print(root)
            break

    #print(root)
    k = k - (l+1) if k - (l+1) >= 0 else k
    print(root[k%len(root)])
if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
idx_appearence = [False] * n
idx_appearence[0] = True
arrival_idx = a[0] - 1
idx_appearence[arrival_idx] = True
idx_lst = [0, arrival_idx]
for i in range(k):
    arrival_idx = a[arrival_idx] - 1
    if idx_appearence[arrival_idx] == False:
        idx_lst.append(arrival_idx)
        idx_appearence[arrival_idx] = True
    else:
        idx_lst.append(arrival_idx)
        break
if i + 1 == k:
    print(idx_lst[-1])
else:
    former_part_len = idx_lst.index(idx_lst[-1])
    recursive_len = len(idx_lst) - 1 - former_part_len
    print(idx_lst[former_part_len + ((k - former_part_len) % recursive_len)] + 1)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import combinations, product
#import bisect# lower_bound etc
#import numpy as np
def run():
    N,K = map(int, sysread().split())
    A = [0] + list(map(int, sysread().split()))
    perm = [1]
    seen = [[-1, False] for _ in range(N+1)]
    seen[1] = [1,True]
    l = 1
    while True:
        v = perm[-1]
        idx, boo = seen[A[v]]
        if boo: break
        l += 1
        perm.append(A[v])
        seen[A[v]] = [l,True]

    if K <= idx -1:
        print(K)
        return None
    K -= idx - 1
    perm = perm[idx-1:]
    print(perm[K % len(perm)])

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
visit=[-1 for i in range(n)]
mark=-1
i=a[0]-1
s=0
n2=n
n3=n
while True:
  if visit[i]!=-1:
    mark=i
    break
  visit[i]=s
  s=i
  i=a[i]-1
loop=0
r=mark
looplist=[]
while True:
  if a[r]==mark+1:
    loop+=1
    looplist.append(r)
    break
  looplist.append(r)
  r=a[r]-1
  loop+=1
i=0
count=0
while True:
  if i in looplist:
    break
  i=a[i]-1
  count+=1
  n3-=1
k-=count
k%=loop
k+=count
ans=1
for i in range(k):
  ans=a[ans-1]
print(ans)

Submission status: Wrong Answer

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

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

graph = []

time = [-1] * N

now = 0
nex = 0
time[0] = 0
loop = 0

while True:
    now = nex
    nex = A[now] - 1

    if time[nex] == -1:
        time[nex] = time[now] + 1
    else:
        loop = nex
        print(time)
        break

if K > max(time):
    K %= (max(time) - time[loop] + 1)
    K -= time[loop]
    tmp = time[loop]
    for i in range(N):
        time[i] -= tmp

for i in range(N):
    for j in range(K + 1):
        if time[i] == j:
            print(i + 1)

# print(time, K)

Submission status: Wrong Answer

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

first = {}
first[1] = 0
second = {}
flag = 1
i = 0
warp = 0
while flag:
    warp += 1
    if A[i] in first.keys():
        second[A[i]] = warp
        flag = 0
        break
    first[A[i]] = warp
    i = A[i] - 1

loop_town = []
stand = 0
for key, value in second.items():
    stand = first[key]
    loop = value - first[key]
    for key2, value2 in first.items():
        if first[key] <= value2 < value:
            loop_town.append(key2) 

print(loop_town[(K-stand)%loop])

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
L=list(map(int,input().split()))
i=1
S=[1]
while(1):
	S.append(L[i-1])
	i=S[-1]
	if len(set(S))!=len(S):
		break
print(S)