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:
n,k = list(map(int,input().split()));
a = list(map(int,input().split()));
i = 0;
start = 0;
count = 0;
finished = [0]*n;
while count < n+2 :
    #print(i,count)
    finished[i] = 1;
    i = a[i]-1;
    count += 1;
    if finished[i] :
        start = i;
        break;
    #print(i,count,1) 

amari = 0;
if count > n :
    ans = i+1;
else :
    i=0;
    count = 0;
    while count < n+1 :
        i = a[i]-1;
        count += 1;
        if i == start :
            break;
    tostart = count;
    i=start;
    count = 0;
    while count < n+1 :
        i = a[i]-1;
        count += 1;
        if i == start :
            break;
    #print(tostart,count);
    amari = (k-tostart)%count;
    i = start;
    for j in range(amari) :
        i = a[i]-1;
    ans = i+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)%m
ss = 0
for i in range (p+ q-1):
    ss = A[ss]-1
print(A[ss])

Submission status: Wrong Answer

Solution code:
import numpy as np
N, K = (int(i) for i in input().split())  
A = [int(i) for i in input().split()] 

def has_duplicates(seq):
  return len(seq) != len(set(seq))

lis = [1]
idx = 0
for i in range(N):
  lis.append(A[idx])
  if has_duplicates(lis):
    lis.pop(-1)
    found = lis.index(A[idx])
    lis.append(A[idx])
    break
  idx = A[idx]-1
  
print(lis[found:i+1][(K-found) % (i - found + 1)])

Submission status: Wrong Answer

Solution code:
N ,K = map(int, input().split())
A = list(map(int, input().split()))
B = [0]
C = {} 
C[0] = 0
cnt = 0
jdg = 0
q = 0
while jdg == 0:
    i = A[q]-1
    q = i
    if q in C:
        l = C[q]
        #print(q,l)
        break
    cnt += 1
    B.append(i)
    C[i] = cnt
r = cnt+1
#print(q)
#print(B)
#print(C)
#print(l)
#print(r)
H = B[l:r]
#print(H) 
M = (K-l)%(r-l)
#print(N-l,M)
print(H[M]+1)

Submission status: Wrong Answer

Solution code:
import sys
N,K = map(int,input().split())
A = list(map(int,input().split()))
last_visited = [-1]*N
now = 1
for i in range(K):
  now = A[now-1]
  if last_visited[now-1] != -1 or now == 1:
    print(last_visited.index((K % (i+1))-1)+1)
    sys.exit()
  last_visited[now-1] = i
print(now)

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
for i in range(200000):
    i += 1
    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()))

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 = list(map(int,input().split()))
adj_list=[0]*N
for i in range(N):
    adj_list[i]=(A[i])
k=0
node = 1
c=[0]*N
count=1
flag=0
ROOP=[]
roopstart=0
while k<K:
    k+=1
    c[node-1]+=1
    node = adj_list[node-1]
    if c[node-1] ==1:
        if flag ==0:
            roopstart = k
            flag=1
        ROOP.append(node)
    if c[node-1] ==2:
        break
l = len(ROOP)
if l != 0:
    num = (K-l-roopstart) % (l)
    print(ROOP[num])
else:
    print(A[node-1])

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = (int(x) for x in input().split())
A = [int(x) for x in input().split()]
roop = 0
x = 0

for i in range(K):
    x = A[x]-1
    if x == 0:
        roop = i+1
        break

x = 0
if roop != 0:
    number = K % roop
    for i in range(number):
        x = A[x]-1

print(x+1)

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)%loop
        for i in range(s, K):
            p = A[p - 1]
        print(p)
    


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
N, K = list(map(int,input().split()))
move_list = list(map(int,input().split()))
 
  
test = 1
find_f = {}
for i in range(N):
  find_f[i+1]=[]
 
find_f[1].append(0)
for i in range(K):
  test = move_list[test-1]
  find_f[test].append(i+1)
  if len(find_f[test]) == 2 and find_f[test][1]-find_f[test][0]<=100000:
    state ,f = test, find_f[test]
    break
try:
  K = K-f[0]
  f = f[1]-f[0]
  remain = K%f
except:
  print(test)
  sys.exit()
 
for i in range(remain):
  state = move_list[state-1]
 
  print(state)

#state = 1

Submission status: Wrong Answer

Solution code:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
#      .      '                    Udit Gupta @luctivud         ,              
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                            ##     ##  #######  # #  ######
                            ##     ##  ##   ##  ###    ##
                            ##     ##  ##    #  # #    ##
                            #########  #######  # #    ##
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import sys
import math as mt
# sys.setrecursionlimit(10**6)

def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))

def printwsp(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")
def printchk(*args): return print(*args, end="tst, ")

MOD = int(1e9+7); BABYMOD = 998244353;
# ################################ HELPER PROGRAMS USED ###################################
# ################################## MAIN STARTS HERE #####################################
# for _testcases_ in range(int(input())):
n, ki = get_ints()
li = get_array()
pos = [0] * (n+1)
vis = [0] * (n+1)
d = {}
curr = 1
k = 0
while True:
    # print(curr, end="->")
    vis[curr] += 1
    if vis[curr] == 2:
        break
    pos[curr] = k
    d[k] = curr
    curr = li[curr-1]
    k += 1

period = k - pos[curr]
ini = pos[curr]
ki -= ini
# ki -=1
left = ki % period
# print(vis, pos, d)
# print(period, ini, k)
print(d[ini + left])


# #########################################################################################
'''
THE LOGIC AND APPROACH IS BY ME @luctivud.
SOME PARTS OF THE CODE HAS BEEN TAKEN FROM WEBSITES LIKE::
4 5
3 2 4 1
(I Own the code if no link is provided here or I may have missed mentioning it)
: DO NOT PLAGIARISE.
'''

Submission status: Wrong Answer

Solution code:
#coding:utf-8

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

B = input().split()
A = [int(i) for i in B]

track = [0] * (N)

state = 1

for i in range(N):
    
    if track[state-1] == 1:
        break
    else:
        track[state-1] = 1

    state = A[state-1]

numnum = 0
path = 0
stopper = state

for i in track:
    numnum += i

state = 1

for i in range(N):
    
    if state == stopper:
        break
    else:
        path += 1
        numnum -= 1

    state = A[state-1]

root = int((K - path) % numnum)
state = 1

for i in range(root + path):
    state = A[state-1]

print("{}".format(state))

Submission status: Wrong Answer

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

# 1から順に探索
visited=[-1]*(1+n)
cl=[0]*(1+n)
visited[1]=0
c=0
now=1
t=0

start=0

for i in range(1,n+1):
    if visited[al[now]]==-1: # まだきてない
        visited[al[now]]=0
        c+=1
        cl[al[now]]=c
        now=al[now]
    else:  
        start=cl[al[now]]
        t=i-start
        break
        
print(cl.index(start+(k-start)%t))

Submission status: Wrong Answer

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

    A    = [int(i)-1 for i in input().split()]
    visit_plan = [0]
    vpi        = 0
    loop_flg     = False
    B    = set(visit_plan)
    for i in range(N-1):
        a = A[vpi]
        if a in B:
            loop_flg = True
            break
        else:
            visit_plan.append(a)
            B.add(a)
            vpi = a


    if loop_flg:
        loop_start = visit_plan.index(a)
        loop_end   = len(visit_plan)
        loop_length = loop_end - loop_start
        last_index = (K-loop_start)%loop_length
        current_town = visit_plan[loop_start+last_index]
    else:
        current_town = a
    print(current_town+1)


if __name__ == '__main__':
    main()

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])
    if k == 0:
        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) % m
for i in range (p+q+1):
    s = A[s]-1
    ANS = A[s]
print(ANS)

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])

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

def loops(A,K):
  C=[0 for _ in range(N+1)]
  s=A[1]
  h=1
  for _ in range(N*2):
      if C[s]<1:
          C[s]+=1
          h+=1
          s=A[s]
      else:
        x=s
        s=A[s]
        b=1
        while x!=s:
            b+=1
            s=A[s]
        return h,b
          
head,body=loops(A,K)
K=(K-head)%body
s=A[1]
for i in range(head+body+K-1):
    s=A[s]    
print(s)

Submission status: Wrong Answer

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

# from fractions import gcd
from math import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement

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

index = 0
dict_root = { i:0 for i in range(N)}
rootnum = 1

ho = 0

for i in range(N):
    dict_root[index] = rootnum

    if dict_root[A[index]-1] != 0:
        ho = dict_root[A[index]-1] - 1
        break
    rootnum += 1
    index = A[index] - 1

nokori = (K-ho) % (rootnum-ho) + 1

for key, value in dict_root.items():
    if value == nokori+ho:
        print(key+1)
        break

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]
towns_kai = [int(town) for town in input_line if int(town) != input_line.index(town) + 1]

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

print(now)

Submission status: Wrong Answer

Solution code:
from time import time
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
L = [-1 for i in range(N)]

visited = []
now = 0
loopstarts = None
looplength = None
t0 = time()

for i in range(N):
    if L[now] != -1:
        break
    else:
        L[now] = i
        visited.append(now)
        now = A[now]-1

loopstarts = visited.index(now)
looplength = len(visited)-loopstarts

if K < loopstarts:
    print(visited[K]+1)
else:
    print(visited[loopstarts+(K-loopstarts)%looplength]+1)
print(time()-t0)

Submission status: Wrong Answer

Solution code:
n, k=input().split()
a=input().split()
a=list(map(int,a))
a=list(map(lambda x: x-1,a))
n=int(n)
k=int(k)
cycle=0
step=0
now=0
ini=0
now2=n
count=[0]*n
count[0]=1

while True:
  now=a[now]
  k+=-1
  if count[now]==1:
    ini=now
    while now2!=ini:
      if cycle==0:
        now2=ini
      now2=a[now2]
      cycle+=1
    else:
      k=k%cycle
      break
  count[now]=1

for j in range(k):
  now=a[now]

       

print(now+1)

Submission status: Wrong Answer

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

visited = [0] * (n + 1)
now = 1
check = 2 * n
loop_start = 1
while check > 0:
    if visited[now - 1] == 1:
        loop_start = now
        break
    else:
        visited[now - 1] += 1
        now = a[now - 1]
        check -= 1

visited = [0] * (n + 1)
now = loop_start
check = n
loop = 0
while check > 0:
    if visited[now - 1] == 1:
        break
    else:
        visited[now - 1] += 1
        now = a[now - 1]
        check -= 1
        loop += 1

now = 1
while k > 0:
    if now == loop_start:
        k %= loop
        if k <= 0:
            break
        else:
            now = a[now - 1]
            k = min(k - 1, 0)
    else:
        now = a[now - 1]
        k -= 1

ans = now
print(ans)

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] and K > 0:
    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())
Line = [int(s) for s in input().split()]

X = [-1]*N

# print(X)
ikisaki = Line[0]
X[0] = 0

# print(ikisaki)

for i in range(N+1):
    if X[ikisaki-1] == -1:
        X[ikisaki-1] = i + 1
        ikisaki = Line[ikisaki-1]
    else:
        warukazu = i+1 - X[ikisaki-1]
        break
    # print(X)

# print(warukazu)
Z = K%warukazu
# print(Z)

print(X.index(Z)+1)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
s=1
l=list()
while True:
    l.append(s)
    s=a[s-1]
    if len(set(l))!=len(l):
            m=l.index(l[-1])
            M=len(l)-1
            break
k=(k-m)%(M-m)
print(l[k+m])

Submission status: Wrong Answer

Solution code:

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

map = {}
for i in range(N):
    map[i+1] = A[i]

visited = {}
note = []
locate = 1
visited[1] = True
note.append(A[0])

i = 1
skippedFlg = False
while True:
    if i > K:
        break
    locate = map[locate]
    if locate in visited and not skippedFlg:
        # print("visitted!")

        diff = 0
        for j in range(len(note)-1,-1,-1):
            diff += 1
            if note[j] == locate:
                break

        i = i - diff + ( diff * (K // diff))
        skippedFlg = True
    else:
        visited[locate] = True
        note.append(locate)

    i += 1

print(locate)

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
    while idx < N:
        if dones[next-1] > 1:
            loop.append(datas[next-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)

Submission status: Wrong Answer

Solution code:
a,b=map(int,input().split())
city=list(map(int,input().split()))
ne=[0]*(50000)
ne[0]=1
for i in range(49999):
    ne[i+1]=city[ne[i]-1]
rpp=[]
nrp=[]
for i in ne[1:25000]:
    if i in ne[25001:50000]:
        rpp.append(i)
for i in ne[0:25000]:
    if i not in ne[25001:50000]:
        nrp.append(i)
if len(nrp)>=b-1:
    print(ne[b])
else:
    print(rpp[((b-len(nrp)-1)%len(rpp))])

Submission status: Wrong Answer

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

a = A[0]
i = 1
while i <= K :
   a = A[a - 1]
   i = i + 1

X = (A.index(a))
print(X + 1)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
List=list(map(int,input().split()))
if List[0]==1:
  print(1)
else:
  P=[1]
  a=1
  while P.count(P[-1])==1:
    a=List[a-1]
    P.append(a)
  if K<len(P):
    print(P[K-1])
  else:
    G=P.index(P[-1])
    S=P[(G+1):]
    C=(K-G-1)%(len(S))
    print(S[C])

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

def has_duplicates(seq):
    return len(seq) != len(set(seq))

count = 0
now_town = 1
tmp = []
while count <= K:
#    print(now_town)
    tmp.append(now_town)
    if has_duplicates(tmp):
        y = tmp.index(now_town)
        x = len(tmp)-1
#        print(K-(y+1))
#        print("y", y)
#        print("x", x)
#        print("K-y+1",(K-y+1))
#        print("x-y", x-y)
#        print("amari",(K-y)%(x-y))
        repeat = tmp[tmp.index(now_town):-1]
        print(repeat[(K-y)%(x-y)])
        break
        
    next_town = A[now_town-1]
    now_town = next_town
    count += 1

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
visted = [1]
bre = 0

for i in range(k):
    a = A[visted[-1]-1]
    
    if a not in visted:
        visted.append(a)
    else:
        visted.append(a)
        bre = 1
        break
        
loop_start = visted.index(visted[-1])+1

if bre == 0:
    print(visted[k-1])
else:
    x = len(visted[:loop_start])
    visted = visted[loop_start:]
    print(visted[(k-x)%len(visted)])

Submission status: Wrong Answer

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

N,K = list(map(int, input().rstrip().split()))
A_list = list(map(int, input().rstrip().split()))
#-----
A_list = [0] + A_list[:]  # add dummy-node
visited_list = [1]
visited_set = set([1])


idx = 1
while True:
    next_idx = A_list[idx]
    
    if next_idx in visited_set:
        break
    else:
        visited_list.append(next_idx)
        visited_set.add(next_idx)
        idx = next_idx


start = visited_list.index(next_idx)
roop = len(visited_list) - start

diff = (K - start) % roop
ans = visited_list[start + diff]

print(ans)

Submission status: Wrong Answer

Solution code:
machicount,flycount=map(int,input().split())
teleps=list(map(int,input().split()))
e=len(teleps)
gh=flycount%e
if gh==e-1:
    print(teleps[0])
else:    
    print(teleps[gh+1])

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:
def main(N, K, A):
    i = 0   # 現在地
    memo = []
    while i not in memo:
        memo.append(i)
        i = A[i] - 1    # pythonは一つずれる
    key = memo.index(i)
    roop = memo[key:]
    print(roop[(K - key) % len(roop)] + 1)    # pythonは一つずれる


if __name__ == '__main__':
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))
    main(N, K, A)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)


def dfs(links, n, k, v, p):
    height_from_leaf = 0
    cut_count = 0
    for u in links[v]:
        if u == 0:
            continue
        hgt, cut = dfs(links, n, k, u, v)
        height_from_leaf = max(height_from_leaf, hgt)
        cut_count += cut
    height_from_leaf += 1
    if p != 0 and height_from_leaf == k:
        height_from_leaf = 0
        cut_count += 1
    return height_from_leaf, cut_count


n, k, *aaa = map(int, sys.stdin.buffer.read().split())
links = [set() for _ in range(n)]
for i, a in enumerate(aaa):
    a -= 1
    links[a].add(i)
_, ans = dfs(links, n, k, 0, 0)
if aaa[0] != 1:
    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:
    if 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:
n, k = map(int, input().split())
a = list(map(int, input().split()))
cnt = 0
c = [0] * n
nex = 1
ans = 0
ane = 1
d=0
for i in range(n):
    if c[nex - 1] == 1:
        break
    c[nex - 1] += 1
    ane = nex
    nex = a[nex - 1]
    cnt += 1


cnt2 = 0
nex2 = nex
anex = nex
for i in range(n):
    if c[nex2 - 1] == 2:
        break
    c[nex2 - 1] += 1
    anex = nex2
    nex2 = a[nex2 - 1]
    cnt2 += 1
#print(nex, cnt)
#print(nex2, cnt2)
if k < cnt + cnt2:
    d = k // cnt
    d = k - cnt * d
    #print(123,d)
    if d==0:
        #print(a[ane - 1])
        exit(0)
    for j in range(d):
        #print(ans)
        ans = a[nex - 1]
        nex = ans
    print(ans)
    exit(0)
d = k - cnt
d2 = d // cnt2
d2 = d - cnt2 * d2

#print(d2)
if d2 == 0:
    print(a[anex - 1])
    exit(0)
for i in range(d2):
    #print(ans)
    ans = a[nex2 - 1]
    nex2 = ans
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int, input().split())
A = list(map(int, input().split()))
P = 1
L =[]
while not(P in L):
    L.append(P)
    P= A[P-1]
C = L.index(P)
if N < C:
   print(L[N])
else:
    L = L[C:]
    B=(K-C)%len(L)    
    print(L[B])

Submission status: Wrong Answer

Solution code:
all = input()
towns = int(all.split(' ')[0])
K = int(all.split(' ')[1])
alltele = input().split(' ')
alltele = list(map(int,alltele))
alltele.insert(0,1)
path = [alltele[0]]
idx = alltele[0]
loops = 0
for i in range(1,len(alltele)):
	idx = path[-1]
	tmp = alltele[idx]
	if alltele[idx] not in path:
		path.append(alltele[idx])
	else:
		loops = path.index(alltele[idx])
sub = len(path)- len(path[loops:])
path = path[loops:]
K = K-sub
K %= len(path)
print(path[K])