Problem:


Score: 400 points

Problem Statement

The Kingdom of Takahashi has N towns, numbered 1 through N.

There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.

Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Help the king by writing a program that answers this question.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2



Sample input:
4 5
3 2 4 1


Sample output:
4

Submission status: Wrong Answer

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

now = 1
temp_l = [0]*N
temp_count = [-1]*N
temp_count[0] = 0
for i in range(N):
    pre = now
    now = A[pre-1]
    if temp_l[now-1] == 1:
        end = now
        temp = i+1
        break
    else:
        temp_l[now-1] = 1
        temp_count[now-1] = i+1
    if i == N-1:
        print(temp_count.index(X)+1)
        sys.exit()

s_index = temp_count[end-1]
repeat = temp - s_index
K -= s_index
K = K % repeat

print(temp_count.index(K+s_index)+1)

Submission status: Wrong Answer

Solution code:
from collections import deque, defaultdict
d = deque()
di = defaultdict(int)
N, K = map(int, input().split())
A = list(map(int, input().split()))


d.append(0)
for i in range(N + 10):
    p = d.pop()
    d.append(p)
    d.append(A[p] - 1)


P = []
k = 0
n = 0
for i, v in enumerate(d):
    if (v in P):
        k = i
        n = v
        break
    P.append(v)
    di[v] = i

le = k - di[n]

amari = K % le

if (di[n] == 0):
    print(d[amari] + 1)
    exit()
else:
    print(d[amari + di[n] + 1] + 1)

Submission status: Wrong Answer

Solution code:
if __name__=="__main__":
    N, K = map(int, input().split(' '))
    _town_list = input().split(' ')
    town_list = [int(n) for n in _town_list]

    next_town = town_list[0]
    visited_town = [1]
    visited_town.append(next_town)
    counter = 1

    while True:
        counter += 1
        next_town = town_list[next_town-1]
        if next_town in visited_town:
            repeated_town_idx = visited_town.index(next_town)
            loop_num = counter - repeated_town_idx
            print(visited_town[(K-repeated_town_idx)%loop_num + repeated_town_idx])
            break
        visited_town.append(next_town)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
As = list(map(int,input().split()))
As_io = [-1]+[-1]*(N-1)


to = As[0]
# print("------")
# print("1",end="->")
for i in range(K):
    # print(str(to), end="->")

    if to == As_io[to-1]:
        print(to)
        break
    
    elif As_io[to-1] > -1:
        # print("\n")
        # print("now loop")
        cycle = i+1-As_io[to-1]
        # print(cycle)
        remain =  (K-(i+1)) % cycle
        
        # print(remain)
        for j in range(remain):
            to = As[to-1]
        print(to)
        break
        
    else:
        As_io[to-1] = i+1
        to = As[to-1]

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# スペース区切りの整数の入力
N, K = map(int, input().split())
# 文字列の入力
A = list(map(int, input().split()))
#開業されたN個要素を受け付ける
#list = [input() for i in range(N)]
#print(A)
ans=1
rireki = [1]
for i in range(N+1):
    if not A[ans-1] in rireki:
        rireki.append(A[ans-1])
        ans=A[ans-1]
        #print(ans)
        #print(rireki)
    else:
        #print(rireki)
        #print(A[ans-1])
        n = rireki.index(A[ans-1])
        #print(n)
        l = len(rireki[n:])
        #print(l)
        #print(K-i-1)
        a=(K-i-1)%l
        ans=rireki[n:][a]
        break

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
tele = list(map(int, input().split()))
move = [-1]*n
move[0] = 0
now = 0
cnt = 0

while True:
    cnt += 1#移動回数
    now = tele[now] - 1 #移動した先

    if move[now] != -1:#探索済みなら周期を計算しbreak
        cycle = cnt - move[now]
        break
    else:
        move[now] = cnt#未探索ならこれまでの移動回数を記録
#この時cntに格納されている数は周期が起こった直後    

#ループが発生する前の場合
if cnt-1 > k:
    ans = 0
    for i in range(k):
        ans = tele[ans] - 1
#ループが発生する場合
else:
    loop = (k-(cnt))%cycle#ループが起こった余り
    now = now
    for i in range(loop):
        now = tele[now] - 1
print(now+1)

Submission status: Wrong Answer

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

s = [0] * N
p = 1
h = []
while True:
    h.append(p)
    s[p-1] = 1
    p = A[p-1]

    if s[p-1] != 0:
        break
print(h, p)
last = h.index(p)
leng = len(h) - last
rem = (K - last) % leng
print(h[last:][rem])

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
lity=[[0,0] for i in range(N)]
if N<K:
  hata=True
  i=0
  a=0
  j=0
  while hata:
    if lity[i][0]==1:
      a=j-lity[i][1]
      break
    lity[i][0]+=1
    lity[i][1]=j
    i=A[i]-1
    j+=1
  K-=j
  p=K%a
  while p>=1:
    i=A[i]-1
    p-=1
  print(i+1)
else:
  hata=True
  i=0
  a=0
  j=0
  while hata:
    if lity[i][0]==1:
      a=j-lity[i][1]
      break
    lity[i][0]+=1
    lity[i][1]=j
    i=A[i]-1
    j+=1
  print(i+1)

Submission status: Wrong Answer

Solution code:
import math
s = list(map(int, input().split()))
N = s[0]
K = s[1]
l = list(map(int, input().split()))

count1 = 1
hd = [1]
now = 1

for i in range(N):
  now = l[now-1]
  if now in hd:
    break
  else:
    hd.append(now)
    count1 += 1

start = now
count2 = 1
for i in range(N):
  now = l[now-1]
  if now == start:
    break
  else:
    count2 += 1

answer = 1

if K <= count1:
  for i in range(K):
    answer = l[answer - 1]
else:
  answer = start
  new_k = K-count1
  reduced = new_k - ((new_k//count2)*count2)
  print(reduced)
  for i in range(reduced):
    answer = l[answer - 1]

print(answer)

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
A = list(map(int, input().split()))
where = [0 for k in range(N)]
where[0]=1
loop=0
for k in range(N):
    where[k+1] = A[where[k]-1]

    if where[k+1] in where[0:k]:
        li = where[0:k]
        end = k+1
        start = li.index(where[k+1])
        loop = end -start
        break
loopbefore = K -end

loopafter = loopbefore%loop

where2 = where[start:end]

if K < end:
    ans = where[K-1]
else:
    K = K - end
    j = K % loop
    ans = where2[j]
 
print(ans)
'''
where2 = [where[end]]
for k in range(loopafter):
    where2.append(A[where2[k]-1])
print(where2[-1])
'''

Submission status: Wrong Answer

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

count = 1
history = [1]
index = -1

while count <= K:
    current = history[-1]
    _next = A[current - 1]
    if _next in history:
        index = history.index(_next)
        break
    else:
        history.append(_next)
    count += 1

if index == -1:
    print(history[-1])
else:
    q, mod = divmod(K - count - (len(history) - index), len(history))
    print(history[mod - 1])

Submission status: Wrong Answer

Solution code:
def main():
    n,k = map(int,input().split())
    a = list(map(int,input().split()))
    b = [-1]*n
    c = [-1]*n
    b[0],c[0] = 0,1

    idx = 1
    cnt = 0
    while True:
        cnt += 1
        if b[a[idx-1]-1] != -1:
            break
        b[a[idx-1]-1] = cnt
        c[cnt] = a[idx-1]
        idx = a[idx-1]
    
    rep = cnt-b[a[idx-1]-1]
    if k < rep:
        print(c[k])
    else:
        k -= b[a[idx-1]-1]+1
        print(c[k%rep])
    return 0

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.readline

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

    # N = 2*(10**4)
    # K = 10**18
    # A = [i+2 for i in range(N)]
    # A[-1] = 1
    # print(A)

    visited = [0]
    visited_set = set([0])
    now = 0
    ind = 0
    my_append = visited.append
    my_add = visited_set.add
    for i in range(K):
        a = A[now]-1
        if a in visited_set:
            ind = i
            break
        else:
            my_add(a)
            my_append(a)
            now = a
            # ind = i

    loop_visited = visited[ind:]
    ans_ind = (K-ind) % len(loop_visited)

    print(loop_visited[ans_ind]+1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N,K = map(int, input().split())
A = list(map(int, input().split()))
p = 1
p_hist = []
while p not in p_hist:
    p_hist.append(p)
    p = A[p-1]
end_loop = p_hist[-1]
end_loop_idx = p_hist.index(end_loop)
start_loop = A[end_loop - 1]
start_loop_idx = p_hist.index(start_loop)
print(p_hist[(K-start_loop_idx)%(end_loop_idx-start_loop_idx+1)+start_loop_idx])
'''
print(p_hist)
print(start_loop, start_loop_idx)
print(end_loop, end_loop_idx)
'''

Submission status: Wrong Answer

Solution code:
import numpy as np
import functools
import math
import collections
import scipy
import fractions
import itertools

def solve():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    now = 0
    hoge= []
    bit = 0
    piyo = 0
    huga = []
    for i in range(k):
        hoge.append(now)
        now = a[now]-1
        if now in hoge:
            huga = hoge[hoge.index(now):len(hoge)]
            piyo = hoge.index(now)
            bit = 1
            break
    if bit == 1:
        ans = huga[(k-piyo)%len(huga)]
        print(ans+1)
    else:
        now = 0
        for i in range(k):
            now = a[now]-1
        print(now)
    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

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

i=0
locate=1
flag=[0]*n
flag2=0
while(True):
    flag[locate-1]+=1
    if flag[locate-1]==2 and flag2==0:
        i=0
        flag2=1
    elif flag[locate-1]==3:
        break
    locate=a[locate-1]
    i+=1
k=k%i+i
locate=1
for j in range(k):
    locate=a[locate-1]
print(locate)

Submission status: Wrong Answer

Solution code:
N = [int(e) for e in input().split()]
nums = [int(t) for t in input().split()]
count=[]
h = True
k=0
check = []
for i in range(N[0]):
    count.append(0)
while h:
    t = nums[k]
    if(t in check):
        break
    else:
        check.append(t)
    k = t -1
s = check.index(t)
ans = (N[1] - s)%(len(check)-s)
ans1 = check.index(t) - 1 + ans
print(check[ans1])

Submission status: Wrong Answer

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

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

T = []

a = A[0]
x = True

while x:
    T.append(a)
    a = A[a-1]
    if a in T:
        x = False

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

Submission status: Wrong Answer

Solution code:
def main():
    N,K=map(int,input().split())
    A=list(map(int,input().split()))
    pos=set()
    pos.add(0)
    i=0
    traversal=[0]
    start=0
    nodes=[1]
    while(start<K):
        position=A[i]-1
        if position in pos:
            break
        traversal.append(position)
        pos.add(position)
        start+=1
        nodes.append(A[i])
        i=position
    if start==K:
        print(A[traversal[-1]])
    else:
        ind=traversal.index(position)
        interval=len(traversal)-ind
        print(nodes[ind+((K-ind)%interval)])
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
lity=[[0,0] for i in range(N)]
if N<K:
  hata=True
  i=0
  a=0
  j=0
  while hata:
    if lity[i][0]==1:
      a=j-lity[i][1]
      break
    lity[i][0]+=1
    lity[i][1]=j
    i=A[i]-1
    j+=1
  K-=j
  p=K%a
  while p>=1:
    i=A[i]-1
    p-=1
  print(i+1)
else:
  hata=True
  i=0
  a=0
  j=1
  while hata:
    if lity[i][0]==1:
      a=j-lity[i][1]
      break
    lity[i][0]+=1
    lity[i][1]=j
    i=A[i]-1
    j+=1
  print(i)

Submission status: Wrong Answer

Solution code:
# D - Teleporter

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

nxt = 1
visited_num = [1]
visited = [False] * N
visited[0] = True
first = []
repeat = []
for _ in range(N):
    nxt = A[nxt - 1]
    if visited[nxt - 1]:
        i = visited_num.index(nxt)
        if i != 0:
            first = visited_num[:i]
            repeat = visited_num[i:]
        break
    else:
        visited_num.append(nxt)
        visited[nxt - 1] = True

if 0 == len(repeat):
    ans = visited_num[K % len(visited_num)]
else:
    ans = repeat[(K - len(first)) % len(repeat)]
print(ans)

Submission status: Wrong Answer

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

pattern = []
p=1
for i, j in enumerate(a):
  pattern.append(a[p-1])
  p = a[p-1]
  if a[p-1] in pattern:
    s = pattern[pattern.index(a[p-1]):]
    break
print(pattern[k%len(s)-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np
n, k = map(int, input().split())
An = list(map(int, input().split()))
root = deque([1])
check = np.zeros(n, np.int)
check[0] = 1
i = 0
dup = 1
cnt = 1
for _ in range(n):
    temp = An[i]
    if check[temp-1] == 1:
        dup = temp
        break
    root.append(temp)
    check[temp-1] = 1
    i = temp - 1
    cnt += 1
index = root.index(dup)
print(root[(k-index) % (cnt-index) + index] if index != cnt-1 else dup)

Submission status: Wrong Answer

Solution code:
paramN, paramK = list(map(lambda x: int(x), input().split(' ')))
paramA = list(map(lambda x: int(x), input().split(' ')))

route = [0] * paramN
route[0] = 1
for i in range(1, paramN):
    route[i] = paramA[route[i - 1] - 1]

loop_start = 0
for i, r in enumerate(route):
    if r in route[:i]:
        loop_start = i
        break

x = route[loop_start]
loop_start_0 = route.index(x)

y = paramK - loop_start_0
z = y % (loop_start - loop_start_0)
print(route[loop_start_0 + z])

Submission status: Wrong Answer

Solution code:
import sys

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

route = [1]
appearance = set()
index = 1
cnt = 0
flg = False
for _ in range(n):
    if index in appearance:
        flg = True
        break
    appearance.add(index)
    cnt += 1
    next_city = A[index - 1]
    route.append(next_city)
    index = next_city

if flg is False:
    print(route[k])
    sys.exit()

# 繰り返し個数
duplicate = route[route.index(index):len(route) - 1]
print(duplicate[(k - cnt) % (len(duplicate))])

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 = [-1] * N
    # dones[next-1] = idx
    loop_cnt = 0
    while idx < N:
        if dones[next-1] < 0:
            dones[next-1] = idx
            next = datas[next-1]
            idx += 1
            continue
        loop_start_idx = dones[next-1]
        loop_end_idx = idx - 1
        loop_cnt = idx - dones[next-1]
        break
    loop = []
    idx = 0
    next = 1
    while idx < N:
        if idx >= loop_start_idx and idx <= loop_end_idx:
            loop.append(datas[next-1])
        next = datas[next-1]
        idx += 1


    idx = ((K-(loop_start_idx))%loop_cnt)-1
    if idx < 0:
        idx += loop_cnt
    print(loop[idx])
#     # idx = 0
#     # next = 1
#     # dones = [False] * N
#     # dones[0] = True
#     # while idx < K:
#     #     if dones[next-1]:
#     #         break
#     #     dones[next-1] = True
#     #     next = datas[next-1]
#     #     idx += 1
#     # loop_cnt = idx + 1
#     idx = 0
#     next = 1
#     dones = [0] * N
#     while idx < N*2:
#         dones[next-1] += 1
#         next = datas[next-1]
#         idx += 1
#     mono_cnt = len(list(filter(lambda x: x == 1, dones)))
#     if K <= mono_cnt:
#         idx = 0
#         next = 1
#         while idx < K-1:
#             next = datas[next-1]
#             idx += 1
#         print(next)
#         exit()
# 
#     loop_cnt = len(list(filter(lambda x: x > 1, dones)))
#     loop = []
#     # for idx, elm in enumerate(datas):
#     #     print(idx, elm)
#     #     if dones[idx] <= 1:
#     #         continue
#     #     loop.append(elm)
#     idx = 0
#     next = 1
#     _cnt = 0
#     while idx < N:
#         if dones[next-1] > 1:
#             if _cnt < loop_cnt:
#                 loop.append(datas[next-1])
#                 _cnt += 1
#         next = datas[next-1]
#         idx += 1
# 
#     idx = ((K-mono_cnt)%loop_cnt) - 1
#     if idx < 0:
#         idx = loop_cnt - 1
#     # print("mono: {}, loop_cnt: {}, idx: {}, loop: {}".format(mono_cnt, loop_cnt, idx, loop))
#     print(loop[idx])
#     # _k = int(K - (K // loop_cnt) * loop_cnt)
#     # idx = 0
#     # next = 1
#     # while idx < _k:
#     #     next = datas[next-1]
#     #     idx += 1
# 
#     # # 出力
#     # print(next)

Submission status: Wrong Answer

Solution code:
def main(N, K, A):
    i = 0   # 現在地
    lst_memo = []
    set_memo = set([])
    while i not in set_memo:
        lst_memo.append(i)
        set_memo.add(i)
        i = A[i] - 1    # pythonは一つずれる
    key = lst_memo.index(i)
    roop = lst_memo[key:]
    if K < key:
        print(lst_memo[K - 1])
    else:
        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:
N, K = map(int, input().split())
A = list(map(int, input().split()))

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

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

    now = A[now - 1]
    first_loop += 1

loop_num = len(loop_node)
first_loop -= loop_num * 2

if K < first_loop:
    now = 1
    for _ in range(first_loop):
        now = A[now - 1]
    print(now)
else:
    print(loop_node[(K - first_loop) % loop_num])

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
if start<=k:
    print(now)
else:
    cl2=cl[1:]
    print(cl2.index(start+(k-start)%t)+1)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
import numpy as np
link = set()
next = a[0]
link.add(1)
while next not in link:
    link.add(next)
    next = a[next-1]

link2 = set()
next2 = a[0]
link2.add(1)
while next not in link2:
    link2.add(next2)
    next2 = a[next2-1]

link2.remove(next)
ans = 0

rep = len(link)- len(link2)

if (len(link2) == 0):
    p = k%rep
    for i in range(p):
        next = a[next-1]
elif(k > len(link2)):
    # print('f')
    p = (k-len(link2))%rep
    # print(p)
    for i in range(p-1):
        next = a[next-1]
else:
    # print('d')
    next = 0
    for i in range(k-1):
        next = a[next-1]

ans = next
# print(link,link2)
print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
#########行列読み込み ##############################################
"""
from sys import stdin
n = int(stdin.readline().rstrip())
data = [stdin.readline().rstrip().split() for _ in range(n)]
print(data)
print(*data, sep='\n')
"""
##################################################################
#########入力系####################################################
"""
s =input()
s=list(input())
a=int(input())
x,y = map(int,input().split())	
li = input().split()	
li = list(map(int,input().split()))	
li = input().split('T')	
"""
##################################################################
n,k = map(int,input().split())
A = list(map(int,input().split()))
l={}

num = [i for i in range(1,n+1)]
print(num)
l = dict(zip(num,A))
print(l)
ans = 1
#print(l[1])
#print(l.keys())
#print(l.values())
for i in range(k):
    ans = l[ans]
print(ans)

Submission status: Wrong Answer

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

A_list = [int(a) for a in input().split()]

# print(N, K)
# print(A_list)

keiro = [1]
visit_town = [0]*N

town = 1
c = 1
while True:
    visit_town[town - 1] = c
    c += 1
    town = A_list[town - 1]
    # print('town', town)

    if len(keiro) > 1 and visit_town[town-1] != 0:
        break
    keiro.append(town)

# print(keiro)
# print(visit_town)
# print(town)


first_visit = keiro[:visit_town[A_list[keiro[-1]-1]-1]-1]
loop_visit = keiro[visit_town[A_list[keiro[-1]-1]-1]-1:]

# print(first_visit)
# print(loop_visit)

if K <= len(first_visit):
    print(first_visit[K - 1])
else:
    l = K - len(first_visit)
    # print(l)
    c = (l) % len(loop_visit)
    # print(c)
    print(loop_visit[c])

# print(keiro[len(first_visit) + (K - len(first_visit)) % len(loop_visit)])

Submission status: Wrong Answer

Solution code:
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
 
def func1(lst, value):
    return [i for i, x in enumerate(lst) if x == value]
  
temp=1
trace=[1]
circle=[]
for i in range(K):
  temp=A[temp-1]
  ans=func1(trace,temp)
  if len(ans)==1:
    circle.append(i-ans[0]+1)
    #print(circle)
    break
  trace.append(temp)
  #print("temp",temp)
#print((K-i)%len(circle)-1)
if len(circle)!=0:
  amari=(K-i)%circle[0]+1
  for j in range(i+amari):
    temp=A[temp-1]

print(temp)

Submission status: Wrong Answer

Solution code:
N,K = [int(i) for i in input().split(' ')]
A = [int(i) for i in input().split(' ')]
 
where_li = []
pre = 0
for i in range(N):
	where_li.append(A[pre])
	pre = A[pre]-1

aa = sorted([x for x in set(where_li) if where_li.count(x) > 1], key=where_li.index)

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = list(map(int, input().split()))
A = np.array(list(map(int, input().split()))) - 1
here = 0
visited = [here]
for i in range(N):
    here = A[here]
    if here in visited:
        idx = visited.index(here)
        break
    visited.append(here)
L = len(visited) - idx
J = K - idx
m = J % L
result = visited[m + idx] + 1
print(result)

Submission status: Wrong Answer

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

now = 1
r = [0]*N
r[0]=now
for i in range(N):
  if A[now-1] in r:
    x = r.index(A[now-1])
    break
  else:
    now = A[now-1]
    r[i+1]=now
r_x = r[x:]
print(r_x[(K-x)%len(r[x:])])

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
ar = list(map(int, input().strip().split(' ')))
route=[]

Town=1
X=0
loop = False

while loop == False:
      for i in range(0,K):
            X=ar[(Town-1)]
            Town=(X)
            route.append(Town)
            if Town in route:
                  loop=True
                  break
      
S=len(route)
K=K-i
Z=K % S
Z=Z+S

for i in range(0,Z):
      X=ar[(Town-1)]
      Town=X

      
print(Town)

Submission status: Wrong Answer

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

if k<=n:
    #k回シミュレートすればよい
    now=0
    for i in range(1,k+1):
        now=a[now]
    print(now+1)
    exit()

now=0
visited=[-100]*n
visited[now]=0
for i in range(1,2*10**5+1):
    now=a[now]
    if visited[now]==-100:
        visited[now]=i
    else:
        m=i-visited[now]
        break
k=k%m
while k<n:
    k+=m

for i in range(1,k+1):
    now=a[now]
print(now+1)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
loop = []
loop.append(1)
n = A[0]
i = 0
while i <= K:
    i += 1
    if n in loop:
        idx = loop.index(n)
        flag = 1
        loop = loop[idx:].copy()
        break
    loop.append(n)
    n = A[n-1]
r = K % len(loop)
print(A[r])

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
import numpy as np
link = set()
next = a[0]
link.add(1)
while next not in link:
    link.add(next)
    next = a[next-1]

link2 = set()
next2 = a[0]
link2.add(1)
while next not in link2:
    link2.add(next2)
    next2 = a[next2-1]

link2.remove(next)
ans = 0

rep = len(link)- len(link2)

if (len(link2) == 0):
    p = k%rep
    for i in range(p):
        next = a[next-1]
elif(k > len(link2)):
    p = (k-len(link2))%rep
    for i in range(p-1):
        next = a[next-1]
else:
    next = 0
    for i in range(k-1):
        next = a[next-1]

ans = next
print(ans)

Submission status: Wrong Answer

Solution code:
# from math import factorial,sqrt,ceil,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
# import networkx as nx
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb

# slist = "abcdefghijklmnopqrstuvwxyz"
N,K = map(int,input().split())
lisA = [0] + list(map(int,input().split()))
# arrA = np.array(input().split(),dtype=np.int64)

checked = {1:0}
roopstnum = 0
i = 1
for n in range(1,N+2):
    if not lisA[i] in checked:
        checked[lisA[i]] = n
        i = lisA[i]
    else:
        roopstnum = lisA[i]
        roopstidx = checked[roopstnum]
        rooplen = n - roopstidx
        break

# print(roopstnum,rooplen,roopstidx,checked)
warukazu = rooplen
for k,v in checked.items():
    if (K-roopstidx) % warukazu == v - roopstidx:
        ans = k
print(ans)
# print(*ans)   # unpackして出力。間にスペースが入る
# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
a=[int(x)-1 for x in list(input().split())]
way=[0]
noappear=[i for i in range(n)]
while True:
        now=way[-1]
        way.append(a[now])
        
        if way[-1] in way[0:-1]:
                break


last=way[-1]
st=way.index(last)
en=len(way)-1
step=en-st
rest=k%step
if k>=en:
        ans=way[rest]+1

else:
        ans=way[k]+1
print(ans)