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:
from math import factorial as fact
import math
import sys
import itertools
import numpy as np
from collections import Counter
import datetime
from collections import deque

#入力:N(int:整数)
def input1():
	return int(input())

#入力:N,M(int:整数)
def input2():
	return map(int,input().split())

#入力:[n1,n2,...nk](int:整数配列)
def input_array():
	return list(map(int,input().split()))

def keta(N):
	return len(str(N))


def input_daytime(input_time):
	time,distance=input_time.split()
	t=time.split(":")
	se=str(t[-1]).split(".")
	dt1 = datetime.timedelta(hours=int(t[0]),minutes=int(t[1]),seconds=int(se[0]),milliseconds=int(se[1]))
	return dt1

def combinations(n,r):
	return list(itertools.combinations(range(n),r))



def all_sets(num_list):
	subsets=[]
	for i in range(2,len(num_list) + 1):
		for c in combinations(num_list, i):
			subsets.append(c) 
	return subsets

#公約数の列挙
def ch(x1):
	cf=[]
	for i in range(2,math.sqrt(x1)+1):
		if x1 % i==0:
			cf.append(i)
	return cf

def CountOneRoots(x,y):
	#x:縦，y:横
	return fact(x+y)/fact(x)/fact(y)

# 素因数分解
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a
	
def count_str(m):
	tmp={}
	for i in range(10):
		if i in tmp:
			tmp[i]=1
		else:
			tmp[i]+=1
	return tmp
		


# n,m,x=input2()
# C=[]
# A=[]

# for i in range(n):
# 	tmp=input_array()
# 	C.append(tmp[0])
# 	A.append(tmp[1:])

# results=[]
# min_r=10000000000
# for j in range(n):
# 	count=0
# 	money=C[j]
# 	X=np.array([x]*m)
# 	X=X-np.array(A[j])
# 	print("j:",A[j])
# 	for k in range(n):
# 		if j!=k:
# 			X=X-np.array(A[k])
# 			money+=C[k]
# 			print(X)
# 			if np.count_nonzero(X<=0)==m and money<min_r:
# 				print(money)
# 				min_r=money
# 				break
# if min_r!=10000000000:
# 	print(min_r)
# else:
# 	print(-1)

n,k=input2()
A=input_array()


junkan=[]
count=0
nums=[]
for i in range(n):
	nums.append(count)
	count=A[count]-1
	if count in nums:
		p=nums.index(count)
		junkan=nums[p:]
		nums=nums[:p]
		break

if k<=len(nums):
	print(nums[k-1])
else:
	num=(k-len(nums))%len(junkan)
	print(junkan[num]+1)

Submission status: Wrong Answer

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

flag = [0]*(N+5) # 何回目に初めて訪れたか 

period = 1
period_pre = 0 # 周期が始まるまでのワープ回数
now = 0
for i in range(N):
  now = A[now]-1
  #print(now+1)
  #print(flag)
  #print()
  if(flag[now] != 0):
    period_pre = flag[now] 
    period = (i+1)-flag[now] 
    break
  flag[now] = i+1

#print('period',period)  
#print('period_pre',period_pre) 
if(period_pre >= K):
  num = period_pre
else:
  num = period_pre+((K-period_pre)%period)
#print('num',num)

now = 0
for i in range(num):
  now = A[now]-1
ans = now+1 # index→town_no  
print(ans)

Submission status: Wrong Answer

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

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

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

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

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

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
lst = list(map(int, input().split()))
lst.insert(0, 0)

times = [0]*(n+1)
_map = [0]*(n+1)
idx = {}

sentou = 0
num = lst[1]
first = 0
kk = 0
for i in range(1, k+1):
    times[num] += 1
    idx[i] = num
    sentou += 1
    if times[num] == 2:
        first = num
        break
    _map[num] = i
    num = lst[num]
    kk += 1

if kk == k:
    print(idx[k])
    exit()


first_idx = _map[first]
num_str = ''
for i in range(first_idx, max(_map)+1):
    num_str += str(idx[i])

ans_len = (k - sentou) % len(num_str)
print(num_str[ans_len])

Submission status: Wrong Answer

Solution code:
n,k= map(int,input().split())
A  = [0]
A += list(map(int,input().split()))
B = [-1 for _ in range(n+1)]
B[1] = 0
now =1
cnt = 0
cic = 0
for i in range(1,n+1):
    now = A[now]
    cnt +=1
    if B[now] ==-1:
        B[now] = cnt
    else:
        cic = cnt - B[now]
        road = B[now] 
        break

if k <= road:
    print(B.index(k)+1) 
else:
    print(B.index(((k-road)%cic+road)))

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]
    k = k - index
    ans_list = ans_list[index + 1:]
    print(ans_list[k % len(ans_list) - 1] + 1)

Submission status: Wrong Answer

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

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

visited = [0] * N

order = []

cur = 1
cnt = 0

while True:
    if visited[cur-1] == 0:
        visited[cur-1] += 1

    elif visited[cur-1] == 1: # cur == 2
        
        order_from_cur = order[order.index(cur):]
        r = (K-cnt) % len(order_from_cur)

        final = order_from_cur[r]
        print(final)
        break
    order.append(cur)
    cur = A[cur - 1]
    cnt += 1

Submission status: Wrong Answer

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

now = a[0]
if k % n == 0:
    k = n
else:
    k = k % n + n

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

print(now)

Submission status: Wrong Answer

Solution code:
# D - Teleporter

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

done = set()
path = []
now = 0
while True:
    if now in done:
        break
    else:
        path.append(now)
        done.add(now)
        now = A[now] - 1

start = path.index(now)
loop = len(path) - start
if K < start:
    steps = K
else:
    steps = (K - start)%loop + start

print(start, loop, steps, path)
print(path[steps]+1)

Submission status: Wrong Answer

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

A0=list(range(N))

def calc_zero(n):
    return n * 0

A0 = list(map(calc_zero, A0))

temp=0
tempv=[]

for i in range(K):
  if A0[temp]>=1:
    loop=i-A0[temp]
    t=(K-A0[temp])%loop
    temp=tempv[A0[temp]+t-1]
    break
  else:
    A0[temp]=i
    temp=A[temp]-1
    tempv.append(temp)
    print(i)
    print(temp)

print(tempv)
print(temp+1)

Submission status: Wrong Answer

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

place = [0]
now = 0
length = 1
while True:
    length += 1
    now = A[now]
    place.append(now)
    place_set = set(place)
    if length != len(place_set):
        break
    

t = place.index(place[length-1])
if K <= t:
    print(place[K-1]+1)
    exit()
K -= t
K %= (length-t-1)
print(place[K+t]+1)

Submission status: Wrong Answer

Solution code:
from collections import deque

N, K = map(int, input().split())
A = list(map(int, input().split()))
stack = deque([])
passed = set()
town = 0
K += 1
while town not in passed:
    passed.add(town)
    stack.append(town)
    town = A[town] - 1

if len(stack) > K:
    print(stack[K])
    import sys
    sys.exit()

tail = 0
while stack[0] != town:
    _ = stack.popleft()
    tail += 1

K -= tail
tmp = K % len(stack)
if tmp == 0:
    tmp = len(stack)
print(stack[tmp - 1] + 1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
As = list(map(int, input().split()))
maps = {}

for i, a in enumerate(As):
    maps[i] = a - 1

s = 0  # カウンター
p = 0  # 初期位置

if (maps[0] == 0):
    print(1)
    exit()

for i in range(n):
    s += 1
    p = maps[p]
    if (p == 0):
        break

d = k % s
ans = 0
for i in range(d):
    ans = maps[ans]

print(ans + 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]
    if machi in s:
        hajime = l.index(machi)
        owari = i-1
        repeat = l[hajime:owari+1]
        print(l)
        break
    x = machi-1
    l[i] = machi
    s.add(machi)
else:
    amari = k%n
    print(l[amari-1])
    exit()

if k < owari:
    print(l[k-1])
else:
    amari = (k-hajime)%len(repeat)
    if hajime + amari == 0:
        print(repeat[-1])
    else:
        print(l[hajime+amari-1])

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=[list(map(int,input().split()))]
if K>=N:
    K=K-(N-1)*int(K/(N-1))
else:
    K=K
def tele(n):
    a=1
    for j in range(0,n+1):
        a=A[0][a-1]
    return(a)

print(tele(K-1))

Submission status: Wrong Answer

Solution code:
from sys import stdin
import sys

N, K = [int(x) for x in stdin.readline().rstrip().split()]
A = list(map(int, input().split()))
B = [i for i in range(1, N+1)]
d = dict(zip(B, A))
t = [0 for i in range(N)]
d1 = dict(zip(B, t))
temp = 1
cnt = 0
ans = []
for i in range(K):
    d1[d[temp]] = d1.get(d[temp], 0)+1
    if d1.get(d[temp], 0) == 2:
        cnt += 1
        ans.append(d[temp])
        # print(i, d[temp])
    if d1.get(d[temp], 0) == 3:
        break
    temp = d[temp]
    if i == K-1:
        print(temp)
        sys.exit()
cnt1 = 0
for i, v in enumerate(d1):
    if v == 1:
        cnt1 += 1
# print(cnt, cnt1, d1, temp, ans)
k = K-1-cnt1
print(ans[k % cnt])

Submission status: Wrong Answer

Solution code:
loop = [1,3,4,5,2,4]
print(loop[:-1].index(loop[-1]))

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
    zm_cnt = len(list(filter(lambda x: x <= 1, dones)))
    if K < zm_cnt:
        idx = 0
        next = 1
        while idx < K:
            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):
        if dones[idx] <= 1:
            continue
        loop.append(elm)
    idx = ((K-zm_cnt)%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:
NK = list(map(int, input().split()))
A = list(map(int, input().split()))

footprints = []
loop = []
start = 0
end = 0
prev = A[0]

footprints.append(1)
for i in range(0, len(A)):
    index = A[prev - 1]
    if (index in footprints):
        start = footprints.index(index)
        end = i + 2
        break
    else:
        footprints.append(index)
        prev = A[prev - 1]

if (start == 0 and end == 0):
    end = NK[0]

prev = A[start]
for i in range(start, end):
    loop.append(A[prev])
    prev = A[prev]

loopStart = NK[1] - start
print(loop[loopStart % len(loop)])

Submission status: Wrong Answer

Solution code:
import sys
#from collections import defaultdict, deque, Counter
#import bisect
#import heapq
#import math
#from itertools import accumulate
#from itertools import permutations as perm
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as combr
#from fractions import gcd
#import numpy as np

stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18

#n = int(stdin.readline().rstrip())
n,k = map(int, stdin.readline().rstrip().split())
A = list(map(int, stdin.readline().rstrip().split()))
#numbers = [[int(c) for c in l.strip().split()] for l in sys.stdin]
#word = [stdin.readline().rstrip() for _ in range(n)]
#number = [[int(c) for c in stdin.readline().rstrip()] for _ in range(n)]
#zeros = [[0] * w for i in range(h)]

# find loop
visited = []
visited.append(0)
next = A[0] - 1
loop = 0
for i in range(n):
    if next in visited:
        loop = i+1-visited.index(next)
        break
    else:
        visited.append(next)
        next = A[next] - 1

road = len(visited) - loop
# 計算
k = k - road
k = k%loop
print(visited[road + k] + 1)

Submission status: Wrong Answer

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

TeList = list(map(int, input().split()))
Tmp = 0
TmpList = [0]

ResultList = []

SetTmp = {0, }
for _ in range(N):
    Tmp = TeList[Tmp] - 1
    if Tmp in SetTmp:
        ResultList = TmpList[TmpList.index(Tmp):]
        break
    else:
        SetTmp.add(Tmp)
        TmpList.append(Tmp)

FirstStep = len(TmpList) - len(ResultList)

if K < len(ResultList):
    print(TmpList[K] + 1)
else:
    print(ResultList[(K - FirstStep) % len(ResultList)] + 1)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
A = list(map(lambda x: int(x) - 1,input().split()))
seen = [0] * N
seen[0] = 1
a = 0
i = A[0]
while True:
    if seen[i]:
        b = A[i]
        a += 1
        break
    seen[i] = 1
    a += 1
    i = A[i]
c = 0
i = A[0]
while True:
    if i == b:
        c += 1
        break
    c += 1
    i = A[i]
d = a - c + 1
is_heiro = False
e = []
i = A[0]
while True:
    if i == b and is_heiro:
        break
    if i == b:
        is_heiro = True
    if is_heiro:
        e.append(i)
    i = A[i]
if K <= a:
    i = A[0]
    for _ in range(K - 1):
        i = A[i]
    print(i + 1)
else:
    a = ((K + 2) - (a - d)) % d
    print(e[a] + 1)

Submission status: Wrong Answer

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

b = 1
while b >= 0:
    if b in A:
        
        break
    if b not in A:
        A.append(b)
        
        b = a[b-1]

c =A.index(b)
d = len(A) -c    

e = (K - (len(A)-d)) % d

print(A[c+e])

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
now = 1
for i in range(min(k, int(2 * n + (n-1)))):
    now = a[now - 1]
print(now)

Submission status: Wrong Answer

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

b = A[0]

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

else:
    for i in range(K):
        c = A[b-1]
        b = c
    ans = b
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
aaa = [0] + list(map(int, input().split()))
cnt = [0, 1] + [0] * (n - 1)
tmp = 1
cic_num = 1
for i in range(1, k + 1):
    tmp = aaa[tmp]
    if cnt[tmp] > 0:
        cic_num = i if tmp == 1 else i - cnt[tmp]
        break
    cnt[tmp] = i
num = (k - cnt[tmp] + 1) % cic_num
print(cnt.index(num + cnt[tmp] - 1))

Submission status: Wrong Answer

Solution code:
import numpy as np

n, k = list(map(lambda x: int(x), input().split(' ')))
teles = list(map(lambda x: int(x)-1, input().split(' ')))

looplen = 0
loop = []

done = False

ni, nj = 0, 0
pi, pj = 0, 0
while True:
  pi = teles[pi]
  pj = teles[pj]
  ni += 1
  nj += 2
  # ni回, piにて確実にループ内
  # ループ一周は nj - ni(= ni)要素&回
  if ni == k:
    print(pi+1)
    done = True
    break
  if pi == pj:
    looplen = ni
    break
    
if not done:
  current = pi
  for i in range(looplen):
    current = teles[current]
    loop.append(current)
  print(loop[(k - ni) % looplen]+1)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
a = input().split()
route = [0]
t = 0
div = [1,0]
lst = []

for i in range(n):
  a[i] = int(a[i])-1
#

while True:
  flg = 0
  t = a[t]
  for i in range(len(route)):
    if route[i] == t:
      flg = i
  if flg:
    div[0] = len(route) - flg
    div[1] = flg % div[0]
    lst = route[flg:]
    break;
  else:
    route.append(t)
#
#print(div)
#print(lst)
print(lst[(k-div[1])%div[0]]+1)

Submission status: Wrong Answer

Solution code:
import collections

def main():
    n, k = map(int, input().split())
    a = [int(i) - 1 for i in input().split()]
    ans = solve(n, k, a)
    print(ans)


def solve(n, k, a):
    arrived = [-1 for i in range(n)]
    path = collections.deque()

    cnt = 0
    pos = 0
    path.append(pos)
    arrived[pos] = cnt

    while True:
        cnt += 1
        pos = a[pos]
        if arrived[pos] != -1:
            break
        arrived[pos] = cnt
        path.append(pos)

    while True:
        if path[0] == pos:
            break
        path.popleft()

    #print(f'{path}')
    #print(f'{arrived[pos]}')

    path = list(path)
    k -= arrived[pos]

    ans = path[k % len(path)]

    return ans + 1


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
if __name__ == '__main__':
    T = input().split()
    N = int(T[0])
    K = int(T[1])
    As = list(map(int, input().split()))
    print(As)
    k = 0
    city = As[k]
    while k < K - 1:
        city = As[city-1]
        k += 1
    print(city)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


N, K = MI()
A = LMI()

d = dict()
seen = set()
i = 0
cur = 0
while True:
    if i > 0:
        cur = A[cur] - 1
    if cur in seen:
        break
    d[i] = cur
    seen.add(cur)
    i += 1

def get_loop_size(start):
    c = start
    size = 0
    while size == 0 or c != start:
        c = A[c] - 1
        size += 1
    return size

for k, v in d.items():
    if v == cur:
        start = k
        break
loop_size = get_loop_size(d[start])
if K < loop_size:
    print(d[K] + 1)
else:
    idx = start + (K - start) % loop_size
    print(d[idx] + 1)

Submission status: Wrong Answer

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

MyList = [int(n) for n in MyList]

ANS = 0
visted = []

def Myfunc(A):
    return MyList[A] - 1

for i in range(K):
    ANS = Myfunc(ANS)
    if ANS in visted:
        beANS = K % (len(visted) - visted.index(ANS))
        ANS = visted[beANS-1]
        print(ANS+1)
        break
    visted.append(ANS)
    if i +1 == K:
        print(ANS+1)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
M = list(map(lambda x: int(x)-1, input().split()))
s = 0
order = [s]
sets = set(order)
while True:
  if M[s] in sets:
    #print(order, M[s])
    if len(order) >= K:
      print(order[K-1]+1)
      break
    K -= order.index(M[s])
    order = order[order.index(M[s]):]
    print(order[K%len(order)]+1)
    break
  order.append(M[s])
  sets.add(M[s])
  s = M[s]

Submission status: Wrong Answer

Solution code:
s = input().split()

n = int(s[0])
k = int(s[1])

a = input().split()

siyouzumi = [1]
t = 1

for i in range(1,k+1):

    t = int(a[t-1])
    if t in siyouzumi:
        haba = i - siyouzumi.index(t) + 1
        kaisu = int((k - i) / haba)

        l = k - (i + (haba * kaisu))

        for j in range(l):
            t = int(a[t-1])
        break

    siyouzumi.append(t)

print(t)

Submission status: Wrong Answer

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

for i in range(n):
  x = a[x-1]
  if not(x in b):
    b.append(x)
  else:
    c = b.index(x)
    break

print( b[c+(k-c) % (len(b)-c)] )

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
a=[0]+p
flag=0
bef=1
town=[1]
town_set=set(town)
cnt=0
while flag==0 and cnt<k:
    if not a[bef] in town_set:
        town.append(a[bef])
        town_set.add(a[bef])
        bef=a[bef]
    else:
        flag=1
        memo=a[bef]
    cnt+=1
if cnt==k:
    print(bef)
    exit()
for j in range(len(town)):
    if town[j]==memo:
        num=j
x=len(town)-num
y=(k-num)%x
print(town[num+y])

Submission status: Wrong Answer

Solution code:
import sys
N, K = map(int, input().split())
A = list(map(int, input().split()))
if K == 1:
    print(A[0])
    sys.exit()
now = A[0]
kiseki = [1]
count = 0
while now not in kiseki:
    kiseki.append(now)
    count += 1
    now = A[now - 1]
    if count == K:
        print(now)
        sys.exit()
ind = kiseki.index(now)
roop = len(kiseki) - ind
nokori = (K - ind) % roop
for i in range(nokori):
    now = A[now - 1]
print(now)

Submission status: Wrong Answer

Solution code:
# D

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

def compute(city, K):
    for i in range(K):
        # print('\t', city)
        city = As[city-1]
    print(city)

cities_visited = [False] * N
i = 0
city = 1
city_visited_time = {}

while not cities_visited[city - 1]:
    # print(city)
    cities_visited[city - 1] = True
    city_visited_time[city-1] = i
    city = As[city-1]
    i += 1

loop_start = city_visited_time[city-1] + 1
loop_end = i + 1

div = (K - loop_start) // (loop_end - loop_start)
# print(loop_start, loop_end, div, K % (loop_end - loop_start + 1))
# compute(city, (K - loop_start) % (loop_end - loop_start) + loop_start)
compute(city, K - loop_start - div * (loop_end - loop_start) + 1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
b = list(map(int, input().split()))
a = [0]
a.extend(b)
#print(a)
count = 1
idou = [0]*(n+1)
idousaki = a[1]
while idou[idousaki] == 0:
  idou[idousaki] = count
  idousaki = a[idousaki]
  count += 1


amari = (k - idou[idousaki]) % (count -idou[idousaki])
print(idou.index((idou[idousaki]+amari)))

Submission status: Wrong Answer

Solution code:

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

for i in range(10000) :
    l = a[l]-1 
    count = +1
    if l == 0 :
        x = k%count
        for i in range(x) :
            l = a[l]-1
            
        print(l+1)
        exit()
        
print(l+1)

Submission status: Wrong Answer

Solution code:
from sys import stdin
import sys

N, K = [int(x) for x in stdin.readline().rstrip().split()]
A = list(map(int, input().split()))
B = [i for i in range(1, N+1)]
d = dict(zip(B, A))
t = [0 for i in range(N)]
d1 = dict(zip(B, t))
temp = 1
cnt = 0
ans = []
for i in range(K):
    d1[d[temp]] = d1.get(d[temp], 0)+1
    if d1.get(d[temp], 0) == 2:
        cnt += 1
        ans.append(d[temp])
        # print(i, d[temp])
    if d1.get(d[temp], 0) == 3:
        break
    temp = d[temp]
    if i == K-1:
        print(temp)
        sys.exit()
cnt1 = 0
for i, v in enumerate(d1):
    if v == 1:
        cnt1 += 1
print(cnt, cnt1, d1, temp, ans)
k = K-1-cnt1
print(ans[k % cnt])

Submission status: Wrong Answer

Solution code:
n,k = map(int ,input().split())
A = tuple(map(int, input().split()))
seen = [-1]*n
tmp = 0
count = 0

while True:
    tmp = A[tmp]-1
    count +=1
    if seen[tmp] != -1:
        seennum = seen.count(1)



        tm = tmp
        se = [-1]*n
        roopmem = []
        while True:
            roopmem.append(tm)
            tm = A[tm]-1
            if se[tm] != -1:
                roop = se.count(1)
                break
            se[tm] = 1
        break
    else:
        seen[tmp] = 1

if k<=n:
    no = 0
    for i in range(k):
        no = A[no]-1
    print(no+1)
else:
    tmp = k-seennum+roop
    tmp %= roop
    print(roopmem[tmp+1]+1)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

""" Input
S = input().rstrip()
N = int(input())
A = np.array(input().split(), dtype=np.float64)
D = [int(input()) for _ in range(N)]
AB = [[int(x) for x in input().split()] for _ in range(N)]
PX = [[int(x) for x in input().split()] for _ in range(Q)]
"""

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

ayumi = [A[0]]
loop = []

counter = 0
flag = True
while True:
    next = ayumi[-1]
    tmp = A[next - 1]

    if tmp in ayumi:
        if flag:
            koremade = len(ayumi)
            start_number = tmp
            counter += 1
            flag = False
            loop.append(tmp)
        else:
            if start_number == tmp:
                break
            counter += 1
            loop.append(tmp)

    ayumi.append(tmp)

a = K
a -= koremade
amari = a % counter

print(loop[amari - 1])

Submission status: Wrong Answer

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

index = 0
keiro = []
s_keiro = set()
loop_f = False

for i in range(k):
  index = al[index] - 1
  if index in s_keiro:
    start = keiro.index(index)
    mod = i - start
    loop_f = True
    break
  s_keiro.add(index)
  keiro.append(index)

if loop_f:
  pos = (k-start) % mod
  if mod == 1:
    print(keiro[start]+1)
  else:
    print(keiro[start + pos - 1]+1)
else:
  print(keiro[-1] + 1)