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: Accepted

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
check=[-1]*n
check[0]=1
ans=[0]
p=0
p=a[p]-1
while check[p]==-1:
  ans.append(p)
  check[p]=1
  p=a[p]-1
ans.append(p)
for i in range(len(ans)-1):
  if ans[i]==ans[-1]:
    x=i
    break
if k<=len(ans):
  print(ans[k]+1)
else:
  print(ans[(k-x)%(len(ans)-1-x)+x]+1)

Submission status: Accepted

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

loop = [1]
arrived = [0] * N
now = 1
arrived[now-1] = 1
for i in range(K):
    now = A[now-1]
    if arrived[now-1] == 0:
        arrived[now-1] = 1
        loop.append(now)
    else:
        loop = loop[loop.index(now):]
        arrive = loop[(K-(i+1))%len(loop)]
        print(arrive)
        exit()
print(now)

Submission status: Accepted

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

appeared = [False] * N
appeared[0] = True
path = [1]
for _ in range(N+10):
    next_A = As[path[-1] - 1]
    if appeared[next_A-1]:
        break
    else:
        path.append(next_A)
        appeared[next_A-1] = True

before_loop = path.index(next_A)
loop_len = len(path) - before_loop

if K <= before_loop:
    print(path[K])
else:
    print(path[(K - before_loop) % loop_len + before_loop])

Submission status: Accepted

Solution code:
N,K = [int(hoge) for hoge in input().split()]
A = [int(hoge)-1 for hoge in input().split()]#0-indexed似直した
Went = [False]* N
curpos = 0
Went[0] = True
asiato = [0]
while 1:
    curpos = A[curpos]
    if Went[curpos]:break
    asiato.append(curpos)
    Went[curpos] = True
Loopstart = asiato.index(curpos)
LenLoop = len(asiato) - Loopstart
#[0 6 2 5 3]2 5 3...
if K < len(asiato):
    print(asiato[K] + 1)
else:
    X = (K - Loopstart) % LenLoop + Loopstart
    print(asiato[X] + 1)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
M = 60
step = [[0]*(M+1) for _ in range(N)]

for i in range(N):
    step[i][0] = P[i]

for i in range(1, M+1):
    for j in range(N):
        c = step[j][i-1]
        c = step[c][i-1]
        step[j][i] = c

c = 0
for j in range(M+1):
    if K % 2:
        c = step[c][j]
    K //= 2
print(c+1)

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp():
    '''
    一つの整数
    '''
    return int(input())
def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))

n, k = inpl()
a = inpl()
now = 1
visited = []
visited_set = set()
FLAG=True
for _ in range(k):
    if now in visited_set:
        FLAG=False
        break
    visited_set.add(now)
    visited.append(now)
    now = a[now - 1]
if FLAG:
    print(now)
    exit()
loop_begin = visited.index(now)
k -= loop_begin
loop_len = len(visited) - loop_begin
print(visited[k%loop_len+loop_begin])

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,k = LI()
    a = LI()
    for i in range(n):
        a[i] -= 1
    p = [[a[i]] for i in range(n)]
    for i in range(60):
        for x in range(n):
            p[x].append(p[p[x][i]][i])
    x = 0
    while k:
        i = int(math.log(k,2))
        x = p[x][i]
        k -= 1<<i
    print(x+1)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

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

dist = [0] * (n + 1)
cur_dist = 0
cur_pos = 1
while True:
    next_pos = a[cur_pos] 
    cur_dist += 1
    if cur_dist == k:
        print(next_pos)
        exit()
    elif dist[next_pos] == 0:
        dist[next_pos] = cur_dist
        cur_pos = next_pos
    else:
        cycle = cur_dist - dist[next_pos]
        nokori = k - cur_dist
        nokori = nokori % cycle
        cur_pos = next_pos
        for i in range(nokori):
            next_pos = a[cur_pos]
            cur_pos = next_pos
            if i == nokori - 1:
                print(cur_pos)
                exit()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
l = [1]
al = [0 for i in range(n+1)]
al[1] = 1
now = 1
for i in range(n):
    nex = a[now-1]
    if al[nex] == 0:
        l.append(nex)
        now = nex
        al[nex] += 1
        if i == n-1:
            goal = nex
    else:
        goal = nex
        break
key = 0
count = 0
roop = []
mae = []
for i in l:
    if key == 0:
        if goal == i:
            key = 1
            roop.append(i)
        else:
            mae.append(i)
            count += 1
    else:
        roop.append(i)
#print(roop,count,mae)
if count > k:
    print(mae[k])
else:
    k -= count
    rp = len(roop)
    k %= rp
    print(roop[k])

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin, log, log10, gcd
from itertools import permutations, combinations, product, accumulate, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
#from fractions import gcd
def debug(*args):
    if debugmode:
        print(*args)
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def FLOAT(): return float(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7
dx = [0, 1, 0, -1, 1, -1, -1, 1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]
debugmode = True

n, k = MAP()
a = LIST()
arr = set([])
loop = []
i = 0
idx = 0
cnt = -1
flag = True
flag2 = True
strt = -1
while i < k:
    idx = a[idx] - 1
    i += 1
    l = len(arr)
    arr.add(idx)
    if l == len(arr) and flag:
        flag = False
        cnt = 1
        strt = idx
        loop.append(idx)
    elif not flag and idx == strt:
        flag2 = False
        break
    elif not flag:
        cnt += 1
        loop.append(idx)
    #debug(idx, loop)
#debug(arr, loop, cnt, flag, flag2)
if flag2:
    print(idx + 1)
else:
    print(loop[(k - i) % cnt] + 1)

Submission status: Accepted

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

def getPath():
    curr = 1
    path = [curr]
    seen = {curr}
    while A[curr - 1] not in seen:
        curr = A[curr - 1]
        path.append(curr)
        seen.add(curr)
    assert A[curr - 1] in seen
    index = path.index(A[curr - 1])
    return path[:index], path[index:]

path, cycle = getPath()
if K + 1 < len(path) + len(cycle):
    print((path + cycle)[K])
else:
    print(cycle[(K - len(path)) % len(cycle)])

Submission status: Accepted

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

recode = [-1]*N
cnt = 0
current = 0
while True:
    if K <= 0:
        print(current+1)
        break
    if recode[current] == -1:
        recode[current] = cnt
        cnt += 1
        current = A[current]
        K -= 1
    else:
        loop = cnt-recode[current]
        K %= loop
        recode = [-1]*N

Submission status: Accepted

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

loop_start=-1
visited={0}
cur=0
while True:
    cur=A[cur]
    if cur in visited:
        loop_start=cur
        break
    else:
        visited.add(cur)


assert loop_start!=-1
#print("start=>",loop_start)

before_loop=0
before_path=[0]
cur=0
while cur!=loop_start:
    cur=A[cur]
    before_loop+=1
    before_path.append(cur)
#print("bef",before_loop)

loop_path=[loop_start]
cur=A[loop_start]
while cur!=loop_start:
    loop_path.append(cur)
    cur=A[cur]
#print("loop=>",loop_path)
#print("llop len=>",len(loop_path))

if K>=before_loop:
    K-=before_loop
    print(loop_path[K%len(loop_path)]+1)
else:
    print(before_path[K]+1)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n): a[i] -= 1
d = [0] * n
nd = [0] * n
r = []
nr = []
i = 0
while True:
    i = a[i]
    if d[i]: break
    d[i] = 1
    r.append(i)
nr.append(i)
nd[i] = 1
while True:
    i = a[i]
    if nd[i]: break
    nd[i] = 1
    nr.append(i)
res = k%len(r)
if len(r) >= k:
    print(r[k-1]+1)
else:
    k -= len(r)
    k %= len(nr)
    print(nr[k-1]+1)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
x=0
t=0
d=[0]*N
v=[-1]*N
while t==0 or x!=0:
    v[x]=t
    t+=1
    if v[A[x]-1]>=0:
        break
    x=A[x]-1
    d[t]=x
c=t-v[A[x]-1]
print(d[K]+1 if K<t else d[(K-t)%c+v[A[x]-1]]+1)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
C=[0]
V=[0]*n
V[0]=1
now=0
for i in range(n):
    now=A[now]-1
    if V[now]==1:
        break
    else:
        V[now]=1
        C.append(now)
loop=C.index(now)
L=len(C)-loop
if k>loop:
    print(C[(k-loop)%L+loop]+1)
else:
    print(C[k]+1)

Submission status: Accepted

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

order = [-1 for i in range(N)]
order[0] = 0
path = [1]

cnt = 1
before = 1
roop_start = -1
while True:
	nxt = A[before - 1]
	if order[nxt - 1] >= 0:
		roop_start = order[nxt - 1]
		break
	order[nxt - 1] = cnt
	path.append(nxt)
	cnt += 1
	before = nxt

L = len(path)
T = L - roop_start

if K < L:
	print(path[K])
	exit()

K -= roop_start
print(path[roop_start + K % T])

Submission status: Accepted

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

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

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

current_pos = 0
steps = 0
first_occurence = {}

result = -1

while steps < k:
	if current_pos in first_occurence:
		first = first_occurence[current_pos]
		cycle_length = steps - first
		left = (k - steps) % cycle_length
		x = 0
		while x < left:
			current_pos = p[current_pos]
			x += 1

		result = current_pos
		break
	else:
		first_occurence[current_pos] = steps
		steps += 1
		current_pos = p[current_pos]

if result == -1:
	result = current_pos

print(current_pos + 1)

Submission status: Accepted

Solution code:
import sys; input = sys.stdin.buffer.readline
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	N, K = getlist()
	A = getlist()
	if K <= 2 * (10 ** 5):
		loc = 0
		for i in range(K):
			loc = A[loc] - 1
		print(loc + 1)
		return

	loc = 0
	for i in range(2 * (10 ** 5)):
			loc = A[loc] - 1

	start = loc
	loop = [loc]
	loc = A[loc] - 1
	while loc != start:
		loop.append(loc)
		loc = A[loc] - 1

	M = len(loop)
	ans = loop[(K - 2 * (10 ** 5)) % M]
	print(ans + 1)
	
	




if __name__ == '__main__':
	main()

Submission status: Accepted

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

seen = [0] * n
node = 0
number = 1
while k:
    if seen[node]:
        loop_length = number - seen[node]
        k %= loop_length
        break

    seen[node] = number
    number += 1
    node = A[node]
    k -= 1


for i in range(k):
    node = A[node]

print(node+1)

Submission status: Accepted

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

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

now = 1
for i in range(n):
    next_town = a[now-1]
    if warp[next_town] == -1:
        warp[next_town] = i+1
        now = next_town
    else:
        break

loop = (i+1) - warp[next_town]
if warp[next_town] > k:
    count = k
else:
    count = (k-warp[next_town])%loop + warp[next_town]

print(warp.index(count))

Submission status: Accepted

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

visit = [False for i in range(N+1)]
now = 1
cnt = 0
while True:
    if visit[now]:
        break
    visit[now] = True
    now = A[now]
    cnt += 1
cnt2 = 0
visit2 = [False for i in range(N+1)]
while True:
    if visit2[now]:
        break
    visit2[now] = True
    now = A[now]
    cnt2 += 1

if cnt >= K:
    ans = 1
    for i in range(K):
        ans = A[ans]

else:
    K -= cnt
    K = K%cnt2
    ans = now
    for i in range(K):
        ans = A[ans]
print(ans)

Submission status: Accepted

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

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

l = [-1] * n
l[0] = 0
now = 0

while True:
    nex = a[now]
    if l[nex] != -1:
        lap = l[now] + 1 - l[nex]
        break
    l[nex] = l[now] + 1
    now = nex

if k <= l[now]:
    print(l.index(k) + 1)
else:
    k = l[nex] + (k - l[nex]) % lap
    print(l.index(k) + 1)

Submission status: Accepted

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

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

count = 0
a = 0
visited = {0:0}
while True:
    count += 1
    K -= 1
    a = A[a]
    if K == 0:
        print(a + 1)
        exit(0)
    if a in visited:
        T = count - visited[a]
        K = K % T
        break
    else:
        visited[a] = count

for i in range(K):
    a = A[a]

print(a + 1)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n):
    a[i] -= 1
INF = 1001001001
dist = [INF]*n
dist[0]=0
now=0
flag = True
while 1:
    to = a[now]
    if dist[to]!=INF and flag:
        loop = dist[now] + 1 - dist[to]
        k-=1
        k %= loop
        flag = False
    else:
        dist[to]=dist[now]+1
        k-=1
    now = to
    if k == 0:
        print(to+1)
        break

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
arr = list(map(int, input().split()))
visited = [-1] * n
visited[0] = 0

i = 0
ptr = 1
while True:
    ptr = arr[ptr-1]
    i += 1
    k -= 1
    if k == 0:
        break
    if visited[ptr-1] != -1:
        k %= i-visited[ptr-1]
    visited[ptr-1] = i
    if k == 0:
        break

print(ptr)

Submission status: Accepted

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

D = [0]
v[0] = 0

cur = A[0]
i = 1

while v[cur] == -1:
    D.append(cur)
    v[cur] = i
    if i == K:
        print(cur+1)
        exit()

    i += 1
    cur = A[cur]

K -= v[cur]
K %= (i - v[cur])

print(D[v[cur] + K]+1)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
tele = list(map(int, input().split()))
times = [0] * N
t = 0
pos = 0
looped = False
while K > 0:
    t += 1
    K -= 1
    if times[pos] == 0:
        times[pos] = t
    elif not looped:
        K %= t - times[pos]
        looped = True
    pos = tele[pos] - 1
print(pos + 1)

Submission status: Accepted

Solution code:
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n,k = map(int,input().split())
A = list(map(int,input().split()))
for i in range(n):A[i] -= 1
visited = [-1] * n
visited[0] = 0
now = 0
count = 0
while True:
  now = A[now]
  count += 1
  if count == k:
    print(now+1)
    exit()
  if visited[now] == -1:
    visited[now] = count
  else:
    rooplen = count-visited[now]
    k -= visited[now]
    k = k % rooplen
    break
  # print(visited)

visited = [-1] * n
count = 0
while True:
  # print(count,k,now)
  if count == k:
    print(now+1)
    exit()
  if visited[now] == -1:
    visited[now] = count
  now = A[now]
  count += 1

Submission status: Accepted

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

history = [None] * N

pos = 0
for idx in range(N + 1):
    if history[pos] != None:
        offset = history[pos]
        step = idx - offset
        break
    else:
        history[pos] = idx
        pos = A[pos] - 1

if K >= offset:
    n_step = (K - offset) // step
    n_targ = K - (offset + n_step * step)
    for _ in range(n_targ):
        pos = A[pos] - 1
else:
    pos = 0
    for _ in range(K):
        pos = A[pos] - 1
        
print(pos + 1)

Submission status: Accepted

Solution code:
N,K=list(map(int,input().split()))
A=list(map(int,input().split()))
next_town=1
_vt=[1]
visited_town={1:0}
for i in range(K):
  now_town=next_town
  next_town=A[now_town-1]
  if next_town in visited_town:
    i_town=_vt.index(next_town)
    K-=i_town
    _vt=_vt[i_town:]
    goal=K % len(_vt)
    print(_vt[goal])
    break
  else:
    _vt.append(next_town)
    visited_town[next_town]=0
else:
  print(next_town)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    A = [i-1 for i in A]
    l = []
    v = set()
    t = 0
    while True:
        l.append(t)
        if t in v:
            break
        v.add(t)
        t = A[t]
    ll = len(l) - 1 - l.index(t)
    loop = l[l.index(t):-1]
    s = l.index(t)
    if K < len(l):
        return l[K] + 1
    K -= s
    K %= ll
    return loop[K] + 1
print(main())

Submission status: Accepted

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

lastVisit = [None] * N
now = 0
n = 0
while lastVisit[now] is None:
    lastVisit[now] = n
    now = As[now]-1
    n += 1
    if n == K:
        print(now+1)
        exit()

for _ in range((K-lastVisit[now]) % (n-lastVisit[now])):
    now = As[now]-1
print(now+1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,K=map(int,input().split())
    A=tuple(map(int1,input().split()))
    used=[False]*N
    v=0
    while True:
        if used[v]==True:
            loopstart=v
            break
        else:
            used[v]=True
        v=A[v]
    v=0
    d0=-1
    for i in range(10**7):
        if v==loopstart and d0==-1:
            d0=i
        elif v==loopstart and d0!=-1:
            d1=i-d0
            break
        v=A[v]
    K-=d0
    if K>0:
        K-=K//d1*d1
    K+=d0
    v=0
    for _ in range(K):
        v=A[v]
    print(v+1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!python3

def LI():
    return list(map(int, input().split()))

# input
N, K = LI()
A = LI()


def main():
    n = 0
    x = 1
    visit = [None] * N
    while visit[x - 1] is None:
        if n == K:
            print(x)
            return
        visit[x - 1] = n
        n += 1
        x = A[x - 1]
    
    v = n - visit[x - 1]
    s = (K - n) % v
    ans = visit.index(visit[x - 1] + s) + 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline 


n,k,*a = list(map(int,read().split()))
for i in range(n): a[i] -= 1


now = 0
cnt = 0
used = [-1]*n

while used[now] == -1:
    used[now] = cnt
    cnt += 1
    now = a[now]
    if cnt == k:
        print(now+1)
        exit()

c = cnt - used[now]
#print(used,cnt,c,now)

k -= used[now]
k %= c
print(used.index(k+used[now])+1)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
arr = list(map(int, input().split()))
i = 1
n = 0
visited = {i:n}
while k > 0:
  n += 1
  k -= 1
  i = arr[i-1]
  if i in visited:
    break
  visited[i] = n

if k == 0:
  print(i)
else:
  k %= n-visited[i]
  while k > 0:
    k -= 1
    i = arr[i-1]
  print(i)

Submission status: Accepted

Solution code:
def main():

    import sys, math
    #from bisect import bisect_left as bl, bisect_right as br, insort
    #from heapq import heapify, heappush, heappop
    from collections import defaultdict as dd, deque
    def data(): return sys.stdin.readline().strip()
    def mdata(): return list(map(int, data().split()))
    def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
    # sys.setrecursionlimit(100000)
    INF = int(1e9)
    mod = int(1e9)+7

    n,k=mdata()
    A=mdata()
    cnt=1
    d=dd(int)
    d1=dd(int)
    d[0]=1
    d1[1]=0
    t=0
    while True:
        if d[A[t]-1]==0:
            cnt+=1
            d[A[t]-1]=cnt
            d1[cnt]=A[t]-1
        else:
            ind1=d[A[t]-1]
            ind2=d[t]
            break
        t=A[t]-1
    if k+1<=ind1:
        print(d1[k+1]+1)
    else:
        k+=1
        k-=ind1
        k=k%(ind2-ind1+1)
        print(d1[(ind1+k)]+1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    f = [True]*n
    cnt = 0
    ans = -1
    x = 0
    while f[x]:
        f[x] = False
        cnt += 1
        x = a[x] - 1
        if cnt == k:
            ans = x+1
            break
    if ans != -1:
        print(ans)
    else:
        k -= cnt
        y = a[x] - 1
        tmp = [x]
        while y != x:
            tmp.append(y)
            y = a[y] - 1
        print(tmp[k%(len(tmp))] + 1)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
from collections import deque
from fractions import gcd
from functools import lru_cache


#############
# Constants #
#############

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

#############
# Functions #
#############

######INPUT######
def inputI(): return int(input().strip())
def inputS(): return input().strip()
def inputIL(): return list(map(int,input().split()))
def inputSL(): return list(map(str,input().split()))
def inputILs(n): return list(int(input()) for _ in range(n))
def inputSLs(n): return list(input().strip() for _ in range(n))
def inputILL(n): return [list(map(int, input().split())) for _ in range(n)]
def inputSLL(n): return [list(map(str, input().split())) for _ in range(n)]

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])
    return arr

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#############
# Main Code #
#############

N,K = inputIL()
A = inputIL()

flag = [False for i in range(N)]
route = [0]

now = 0
flag[0] = True
while True:
  n = A[now]-1
  if flag[n] == True:
    loop_point = n
    break
  route.append(n)
  flag[n] = True
  now = n

p = route.index(loop_point)
path = route[:p]
loop = route[p:]

if K <= len(path)-1:
  print(path[K]+1)
else:
  k = K-len(path)
  k = k%len(loop)
  print(loop[k]+1)

Submission status: Accepted

Solution code:
from collections import defaultdict as dd

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


res = 1
dic=dd(int)

now = 1
mita = set()
mita.add(now)
dic[now] = 1
start = 0
end = 0
# loop
while 1:
    next_town = a[now-1]
    # print(next_town)
    if next_town in mita:
        start = next_town
        end = now
        break
    else:
        res += 1
        now = next_town
        mita.add(next_town)
        dic[next_town] = res
    if res == K+1:
        print(next_town)
        exit()
# print(dic)

loop_num = dic[end] - dic[start] + 1
Kmod = (K-res)%loop_num
# print(K,res,loop_num,Kmod)
now = next_town
for i in range(Kmod):
    next_town = a[now-1]
    now = next_town
print(now)

Submission status: Accepted

Solution code:
def main():

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

    visited = dict()
    visited[1] = 0
    inv_d = dict()
    inv_d[0] = 1
    j = 0
    period = 0
    shift = 0
    for i in range(1, N+1):
        if A[j] in visited:
            period = i-visited[A[j]]
            shift = visited[A[j]]
            break
        else:
            visited[A[j]] = i
            inv_d[i] = A[j]
            j = A[j]-1

    if K <= shift:
        return inv_d[K]
    else:
        return inv_d[(K-shift) % period + shift]



if __name__ == '__main__':
    print(main())

Submission status: Accepted

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

current_town = 0
if k < 200000:
    for i in range(k):
        current_town = a[current_town]
    print(current_town + 1)

else:
    passed = [-1] * n
    passed[0] = 0 
    for i in range(1, 1000000):
        current_town = a[current_town]
        if passed[current_town] > -1:
            start = passed[current_town]
            period = i - start
            break
        else:
            passed[current_town] = i

    m = (k - start) % period
    for i in range(m):
        current_town = a[current_town]

    print(current_town + 1)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Alist = list(map(int, input().split()))
path = [0]
next = Alist[0]
seen = set()
seen.add(0)
while (next-1) not in seen:
    seen.add(next-1)
    path.append(next-1)
    next = Alist[next-1]
base = path.index(next-1)
loop_length = len(path) - base
loop = path[base:base+loop_length+1]
# print(path)
# print(loop, loop_length, base)
if K <= base:
    print(path[K]+1)
else:
    K -= base
    print(loop[K%loop_length]+1)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    N, K = map(int, input().split())
    *A, = map(lambda x: int(x) - 1, input().split())

    P = []
    t = 0
    for i in range(N + 1):
        P.append(t)
        t = A[t]

    t1 = t2 = 0
    t = 0
    first_visit = [-1] * N
    while t <= N:
        town = P[t]
        if first_visit[town] < 0:
            first_visit[town] = t
        else:
            t1 = first_visit[town]
            t2 = t
            break
        t += 1

    term = t2 - t1
    cycle = (K - t1) // term if K >= t1 else 0
    rest = K - term * cycle - t1 if K >= t1 else 0
    ans = P[t1] if K >= t1 else P[K]
    for i in range(rest):
        ans = A[ans]
    print(ans + 1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()



class Doubling():
    def __init__(self, a0, m):
        """
        a0 is an array-like object which contains ai, 0 <= i < N.
        ai is the next value of i.
        """
        N = len(a0)
        self.N = N
        self.nt = [[None] * N for i in range(m.bit_length()+1)]
        for i, a in enumerate(a0):
            self.nt[0][i] = a

        for i in range(1, len(self.nt)):
            for j in range(N):
                if self.nt[i-1][j] is None:
                    self.nt[i][j] = None
                else:
                    self.nt[i][j] = self.nt[i-1][self.nt[i-1][j]]

    def apply(self, i, n):
        """
        Apply n times from i
        """
        j = i
        for k in range(n.bit_length()):
            m = 1 << k
            if m & n:
                j = self.nt[k][j]
            if j is None:
                break
        return j

def slv(N, K, A):
    A = [a-1 for a in A]
    d = Doubling(A, 10**18+1)
    return d.apply(0, K) + 1


def main():
    N, K = read_int_n()
    A = read_int_n()
    print(slv(N, K, A))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
seen = [0 for _ in range(n)]
seen[0] = 1
now = 0
for i in range(n):
  now = a[now] - 1
  if seen[now]:
    gap = i + 2 - seen[now]
    break
  else:
    seen[now] = i + 2
if k <= seen[now] - 1:
  now = 0
  for i in range(k):
    now = a[now] - 1
  print(now+1)
  #print('#')
else:
  #print(now)
  k -= seen[now] - 1
  #print(1,k)
  k %= gap
  #print(2,k)
  for i in range(k):
    now = a[now] - 1
  print(now+1)
  #print(gap)
  #print(seen)