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:
# /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
    z_cnt = len(list(filter(lambda x: x == 0, dones)))
    mono_cnt = len(list(filter(lambda x: x == 1, dones)))
    loop_cnt = len(list(filter(lambda x: x > 1, dones)))
    loop = []
    for idx, elm in enumerate(datas):
        if dones[idx] <= 1:
            continue
        loop.append(elm)
    idx = (K%loop_cnt)-1
    if idx < 0:
        idx = loop_cnt -1
    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)

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=[]
while t!=0:
    to=edge[now-1]
    t-=1
    if to in l:
        break
    else:
        l.append(to)
    now=to

x=len(l)-l.index(to)
y=len(l)-x
cnt=(k-y)%x
print(l[y+cnt-1])

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
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:
n,k=map(int,input().split())
a=list(map(int,input().split()))
t=0
j=0
c=[1]
b={}
for i in range(n):
    j=a[j]-1


    if j+1 in b:

        break
    c.append(j + 1)
    b[j + 1] = 1
m=c.index(a[c[-1]-1])

c=c[m:]

s=(k-m)%(len(c))
print(c[s])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split(" "))
a = list(map(int,input().split(" ")))
memory = [1]
i = 1
while True:
  if not a[i-1] in memory:
    memory.append(a[i-1])
    i = a[i-1]
  else:
    start = memory.index(a[i-1])
    break
if k < len(memory):
  print(memory[k])
else:
  loop = len(memory)-start
  town = (k - start) % loop
  print(memory[town + start],memory)

Submission status: Wrong Answer

Solution code:
# ABC167d


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    # 再帰関数を使わない限りPypyで出すこと

    def dump(*args):
        sys.stderr.write(str(args))

    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    pos = [-1] * n
    pos[0] = 0

    nex = a[0] - 1
    now = 0
    turn = 0

    mode = False

    while True:
        if not mode and pos[nex] == -1:
            pos[nex] = pos[now] + 1
            now = nex
            nex = a[nex] - 1
            turn += 1
            continue
        res = ((k-turn) % (turn - pos[nex] + 1)+turn) % (turn - pos[nex] + 1)
        for i in range(n):
            if pos[i] == res:
                print(i + 1)
                exit(0)
    # print(pos)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
def pri(x): print('\n'.join(map(str, x)))

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

dist = [0]*N
dist[0] = 0
cnt = 0
cp = 0
while cnt < N+10:
    np = A[cp]-1
    if np == cp: # ikidomari
        print(np+1)
        exit()
    elif dist[np]>0 or np == 0: # loop
        lstep = cnt - dist[np] + 1
        cp = np
        break
    dist[np] = cnt + 1
    cp = np
    cnt += 1

K -= dist[cp]
K %= lstep
cnt = 0
while cnt < K:
    np = A[cp]-1
    cp = np
    cnt += 1
    
print(cp+1)

Submission status: Wrong Answer

Solution code:
#D

#デバッグ
debug=1
def pront(*n):
    if debug==1:
        print(n)
        
#10**9+7を底とした処理

base=10**9+7

def add(a,b):#a+b
    return (a+b)%base

def sub(a,b):#a-b
    return (a-b)%base

def multi(a,b):#a*b
    return (a*b)%base

def exp(a,b):#a**b
    x=1
    c=a
    d=b
    while d!=0:
        if d%2==1:
            x=multi(x,c)
        c=(c**2)%base
        d=d//2
    return x

def div(a,b):#a/b
    return(multi(a,exp(b,base-2)))

#入力
N,K=map(int,input().split())

A=list(map(int,input().split()))
B=[0 for i in range(len(A))]
#処理
x=[]
y={}
i=0
j=1
while True:
    if B[i]!=0:
        p=B[i]
        break
    else:
        B[i]=j
        x.append(A[i])
    i=A[i]-1
    j+=1

K=len(x)-p+1

if N<=p:
    print(x[N])
else:
    print(x[((N-p+1)%K)])

#print(x,B,K)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
l = list(map(int, input().split()))
arr = []
check = [0] * (n + 2)
check[1] = 1
c = 0
num = 1
yo = 0
while 1:
    arr.append(l[c])
    if l[c] == 1:
        yo = 1
        break
    if check[l[c]]:
        arr.pop()
        c = l[c]
        break
    check[l[c]] = 1
    num -= -1
    c = l[c] - 1
# print(arr, c)
for i in range(len(arr)):
    if arr[i] == c:
        c = i + 1
        break
if yo == 1:
    print(arr[k % len(arr) - 1])
elif k < c: print(arr[k])
else:
    ne = arr[c - 1: ]
    k = k - (c - 1)
    print(ne[k % len(ne) - 1])

Submission status: Wrong Answer

Solution code:
a = raw_input().split()
n = int(a[0])
k = int(a[1])
a = raw_input().split()
for i in range(n):
    a[i] = int(a[i])
m = []
i = 0
while 1:
    if i in m:
        break
    m.append(i)
    i = a[i] - 1
l = len(m)
s = m.index(i)
res = (k - s) % (l - s)
print m[res + s] + 1

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N,K = LI()
    A = [0] + LI()

    his = [1]
    s = 1
    cnt = 1
    while True:
        s = A[s]
        if s in his: break
        his.append(s)
        cnt += 1

    cnt -= (his.index(s))

    k = (K - his.index(s)) % cnt
    for i in range(k):
        s = A[s]
    print(s)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# coding:utf-8

import sys
import math
import time
#import numpy as np
import collections
from collections import deque
from collections import Counter
import queue
import copy
import bisect
import heapq
import itertools



sys.setrecursionlimit(10**7)
#N, Q = map(int, input().split())
#G = [list(input()) for i in range(H)]
#INF = V * 10001
#A = [int(i) for i in input().split()]
#AB = [list(map(int, input().split())) for _ in range(K)]

N, K = map(int,input().split())
A = [int(i) for i in input().split()]
Temp = [0]*N
imp = [0]*3
ans = [0]

def rec(next, kore):
    #print(kore)
    if(kore==K):
        ans[0] = next
        return
    if(Temp[next-1] == 0):
        Temp[next-1] = kore
        rec(A[next-1], kore+1)
    else:
        imp[0] = kore-Temp[next-1]
        imp[1] = kore
        imp[2] = next
    return

rec(0,1)
#print("fin")
for i in range(N):
    Temp[i] = 0

if(ans[0] != 0):
    print(ans[0])
else:
    K -= imp[1]
    K = K%imp[0]
    if(K==0):
        print(imp[2])
    else:
        rec(imp[2], 1)
        print(ans[0])

Submission status: Wrong Answer

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

v=1
l=[]
for i in range(k):
    v=a[v-1]
    if v in l:
        index=l.index(v)
        l2=l[index:]
        print(l2[(k-index)%len(l2)-1])
        break
    else:
        l.append(v)

Submission status: Wrong Answer

Solution code:
import sys
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())

n,k = MI()
a = LI()

tmp = 0
cnt = 0
b = [0]
for _ in range(n):
    if (a[b[-1]]-1) in b:
        break
    b.append(a[b[-1]]-1)
    cnt += 1
first = b.index(a[b[-1]]-1)
second = len(b)
print(b[(k-first)%(second-first)+first]+1)

Submission status: Wrong Answer

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

A = list(map(int, input().split()))
past = [0]*min(K, 2*10**5)
now = 1
step = 0
for i in range(K):
    past[i] = now
    now = A[now-1]
    if now in past:
        step += 1
        break

if step > 0:
    id = past.index(now)
    step = i+1 - id
    p = (K-id) % step
    now = A[id+p]

print(now)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10**7)

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, k = na()
a = na()
for i in range(n):
    a[i] -= 1
ct = [0 for i in range(n)]
seen = [False] * n
def dfs(v):
    nv = a[v]
    seen[v] = True
    if ct[nv] == k:
        return nv, 0
    if seen[nv]:
        r = ct[v] + 1 - ct[nv]
        l = (k - ct[nv]) % r
        return nv, l
    else:
        ct[nv] = ct[v] + 1
        return dfs(nv)

nv, l = dfs(0)
for i in range(l):
    nv = a[nv]
print(nv + 1)

Submission status: Wrong Answer

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

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

    count = 0
    visited = []
    set_v = set()
    now = 0
    l = -1
    while count < N:
        x = A[now]
        if x in set_v:
            l = visited.index(x)
            break
        else:
            count += 1
            visited.append(x)
            set_v.add(x)
            now = x-1
    r = count
    
    if K < l:
        print(visited[K])
    else:
        print(visited[l + (K-l) % (r-l)-1])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N, K = map(int, input().split())
memo = [-1]*(N+1)
junban = deque()
A = [0]+list(map(int, input().split()))
i = 0
x = 1
while memo[x] < 0:
  junban.append(x)
  memo[x] = i
  x = A[x]
  i += 1
T = i-memo[x]
if K < T:
  print(junban[K])
else:
  print(list(junban)[memo[x]:][(K-memo[x])%T])

Submission status: Wrong Answer

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

h = set([0])
c = 0
for i in range(k):
  c = a[c] - 1
  if c in h:
    break
  else:
    h.add(c)


for i in range(k % len(h)):
  c = a[c] - 1

print(c + 1)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
a =list(map(int, input().split()))
j = a[0]
# c = 1

s = set()

s.add(j)

# again = 0
ag = 0
c = 0
while(True):
	j = a[j-1]
	if(j in s):
		ag = j
		c+=1
		break
	else:
		s.add(j)
		c+=1

st =0
j = a[0]
while(True):
	if(j == ag):
		# ag = j
		st+=1
		break
	else:
		j = a[j-1]
		st+=1

# print(st)
# print(c)
# # st = a.index(st)
# print(ag)
k -= st-1

r = k%(c-st+1)

while(r != 0):
	ag = a[ag-1]
	r-=1
ag = a[ag-1]
print(a[ag-1])

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
l=list(map(int,input().split()))
tl=[-1]*n
tl[0]=0
index=0
i=1
while True:
  index=l[index]-1
  if tl[index]==-1:
    tl[index]=i
  else:
    last=(k-tl[index])%(i-tl[index])
    break
  i=i+1
for i in range(last):
  index=l[index]-1
print(index+1)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
A =[0]+list(map(int,input().split()))
l= 1
a = A[1]
C = [1]

while (not a in C):
  C.append(a)
  a = A[a]

  l += 1
b=A[a]
B = [a]
o=1
while b != a:
  B.append(b)
  b = A[b]
  o += 1


m = (k-l) % o
print(B[m])

Submission status: Wrong Answer

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

li = list(map(int, input().split()))
n = 1
a = []

while True:
  if li[n-1] in a:
    p = li[n-1]
    break
  a.append(li[n-1])
  n = li[n-1]

n = 1
k = 0
x = 0
while True:
  n = li[n-1]
  if p == n:
    if x == 1:
      break
    else:
      x = 1
  if x == 1:
    k += 1

K %= k

n = 1
for i in range(K):
  n = li[n-1]

print(n)

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 not dic[A[a-1]]:
            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
                    break
            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()))

T = []

a = A[0]

while a not in T:
    T.append(a)
    a = A[a-1]

if K <= T.index(a):
    print(T[T.index(a)-1])
else:
    if (K-T.index(a))%(len(T)-T.index(a)) == 0:
        print(T[-1])
    else:
        print(T[T.index(a) + (K-T.index(a))%(len(T)-T.index(a)) - 1])

Submission status: Wrong Answer

Solution code:
n,k =map(int,input().split())
a=list(map(int,input().split()))
count=0
d=dict()
for i in range(n):
    if a[i] in d:
        count+=1
        break
    else:
        d[a[i]]=1
        count+=1
##print(count)
count-=1
k=k%count
ans=1
for i in range(k):
    ans=a[ans-1]


print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = []
ans = a[0]
t = 0 
for i in range(k):
    t = a[ans-1]
    ans = a[t-1]
    if ans in s:
        break
    s.append(ans)
r = k % len(s)
print(s[r-1])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
An = list(map(int, input().split()))
root = [1]
i = 0
dup = 1
for _ in range(n):
    if An[i] in root:
        dup = An[i]
        break
    root.append(An[i])
    i = An[i] - 1
index = root.index(dup)
# print(index)
repeat = root[index:]
# print(repeat)
print(repeat[(k-index)%len(repeat)])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
k += 1
l1 = list(map(int,input().split()))
l = list(i-1 for i in l1)
mi = [0]
m = l[0]
for i in range(2*(10**5+1)):
  if m in mi:
    a = mi.index(m)
    r = mi[a:]
    break
  else:
    mi.append(m)
    m = l[m]
be = mi[:a]+r
#print(be)
if k<= len(be):
  print(be[k])
else:
  w = k-len(be)
  u = w%len(r)-1
  print(r[u]+1)

Submission status: Wrong Answer

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

l = [0]*n
s = set()
x = 0

for i in range(n):
    machi = a[x]
    x = machi-1
    if machi in s:
        hajime = l.index(machi)
        repeat = l[hajime:i]
        break
    l[i] = machi
    s.add(machi)
else:
    amari = k%n
    print(l[amari-1])
    exit()

amari = (k-hajime)%len(repeat)
print(l[hajime+amari-1])

Submission status: Wrong Answer

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

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

loop = False
count = 0
visited = []
i = 1
while(count != k):
	if i in visited: break
	visited.append(i)
	i = a[i-1]
	count += 1
print(visited)
if(count != k):
	itr = k%count
	print(visited[itr])
	# count = 0
	# i = 0
	# while(count != itr):
	# 	i = a[i-1]
	# 	count += 1
	# print(i,visited)
else:
	print(visited[len(visited)-1])

Submission status: Wrong Answer

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

visited_ls = [0] * (n+1)
tour_ls = []
now = 1
times = 0
while True:
    tour_ls.append(now)
    visited_ls[now] += 1

    times += 1
    nex = a_ls[now]
    if visited_ls[nex]:
        first_ind = tour_ls.index(nex)
        before_loop = first_ind
        loop_ls = tour_ls[first_ind:times]
        break
    now = nex
ind = (k - before_loop) % len(loop_ls)
print(loop_ls[ind])

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
a = [i-1 for i in a]
num = [0] * (n)
num[0] = 1
now = 0
for i in range(2,300000):
  nex = a[now]
  if num[nex]:
    start = num[nex]
    cycle = i - num[nex]
    v = (k+1-start) % cycle + start
    ans = num.index(v) + 1
    break
  else:
    num[nex] = i
    now = nex
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N, K = map(int, sys.stdin.readline().split())
A = list(map(int, sys.stdin.readline().split()))

x = A[0]
visited = [1]
for i in range(N):
    if x in visited:
        a = visited.index(x)
        b = i + 1
        break
    visited.append(x)
    x = A[x - 1]
    
n = (K - b) % (b - a)
ans = visited[a + n]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

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

array = [-1] * (n+1)
array[1] = 0

li = []
li.append(1)

tmp = -1
index = 0
for i in range(2 * (10**5)):
  if array[a[index]] != -1:
    tmp = array[a[index]]
    break
    
  if i == k:
    print(a[index])
    sys.exit(0)
    
  li.append(a[index])
  array[a[index]] = i+1
  index = a[index] -1
  
k -= tmp
d = len(li) - tmp

k %= d

print(li[(k+tmp) % d])

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 t>=k:
  print(a.index(k))
else:
  k-=t
  u=k%g
  print(a.index(t+u+1)+1)

Submission status: Wrong Answer

Solution code:
import math
from collections import defaultdict


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

    visited = [-1 for _ in range(N)]
    visited[0] = 0

    current = 0
    for i in range(1, N):
        current = A[current] - 1

        if visited[current] >= 0:
            # print(i, current, visited[current])
            per_loop = i - visited[current]
            th = visited[current]
            break
        else:
            visited[current] = i

    current = 0
    # print(th, per_loop)
    # print(th + (K - th) % per_loop)
    for i in range(th + (K - th) % per_loop):
        current = A[current] - 1

    print(current+1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
now = 1
cnt = 1
loop = 0
visited = [False] * n
visited[now - 1] = cnt
while True:
    now = a[now - 1]
    cnt += 1
    if visited[now - 1]:
        loop = (cnt - visited[now - 1])
        print(a[((k - (visited[now - 1])) % loop) + (visited[now - 1])])
        exit()
    visited[now - 1] = cnt

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
seen = []
start = 1

while True:
    tmp = a[start - 1]
    seen.append(start)
    if tmp in seen:
        repeat_index = seen.index(tmp)
        repeat_len = len(seen) - repeat_index
        break
    start = tmp

print(seen[repeat_index + ((k - repeat_index) % repeat_len)])

Submission status: Wrong Answer

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 = []
    cycle_list = []
    
    cycle = 0
    diff = 0
    counter = 0
    machi = 1
    for num in A_i:
        logging.info("now : " + str(num))
        if machi in B_i:
            logging.info(machi)
            diff = B_i.index(machi)
            cycle = counter - diff
            cycle_list = B_i[diff:]
        else:
            counter += 1
            B_i.append(machi)
            machi = A_i[machi - 1]

    logging.info(cycle)
    mod_K = (K - diff) % cycle

    print(cycle_list[mod_K])

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

l = []
kari = 1


for i in range(N*2):
    l.append(A[kari-1])
    kari = A[kari-1]
    
    zyuuhuku = set(l)
    if len(zyuuhuku) != len(l):
        tometatokoro = A[kari-1]
        break
    


    
    

#繰り返しでもどったところの列番号
aaaa = l.index(tometatokoro)

#繰り返すループの長さ
kurikaesi = len(l)-aaaa

#ループ繰り返す余り
ans = K % kurikaesi


ans = ans + aaaa

#print(l)
#print(ans)
print(l[ans])

Submission status: Wrong Answer

Solution code:
def findCycle(nums, k):
    for idx, val in enumerate(nums):
        nums[idx] = val - 1
    fast = slow = nums[0]
    while 1:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            slow = nums[0]
            while slow != fast:
                slow = nums[slow]
                fast = nums[fast]
            return slow
            
def findLast(nums, k):
    cycleStart = findCycle(nums, k)
    i = 1
    currentNum = nums[0]
    while currentNum != cycleStart:
        i += 1
        currentNum = nums[currentNum]
    cycleLenght = 1
    currentNum = nums[currentNum]
    while currentNum != cycleStart:
        cycleLenght += 1
        currentNum = nums[currentNum]
    
    k = (k - i) % cycleLenght
    result = cycleStart
    while k > 0:
        k -= 1
        result = nums[result]
        
    return result + 1

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

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

P=0
L=[0]
D=[0]*int(N)
c=0
R=0
while(1):
    c+=1
    P=A[P]-1
    if D[P]>0: 
        R=D[P]
        break
    D[P]=c
    L.append(P)
    if P==0: break

#print(L)
K-=R
K%=(c-R)
#print(R,K)
ans=L[R+K]+1

print(ans)

Submission status: Wrong Answer

Solution code:
N,K= list(map(int , input().split()))
A = list(map(int , input().split()))
li = []
k = 0
s = A[0]-1
li.append(A[0])
while k == 0:
    k = li.count(A[s])
    li.append(A[s])
    s = A[s]-1
    if k == 1:
        n = A[s]
q = li.index(n)
m = len(li) - q
p = (K - q+1)%m
for i in range (p+1):
    s = A[s]-1
print(A[s])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
ls = [1,a[0]]
for i in range(20):
    ls.append(a[ls[-1]-1])
print(ls[-2])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import itertools


def search(maps):
  current = 0
  passed = [0]
  while True:
    current = maps[current]
    if current in passed:
      base = passed.index(current)
      return (base, len(passed) - base)

    passed.append(current)


def main():
  N, K = map(int, input().split(' '))
  maps = [m - 1 for m in map(int, input().split(' '))]

  # 探索
  base, cycle_len = search(maps)

  if K <= base:
    print(maps[K] + 1)
  else:
    print(maps[((K - base) % cycle_len) + base] + 1)


if __name__ == '__main__':
  main()