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: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
l=list(map(int,input().split()))
c=[0]*n
d=[0]*n
g=0
count=1
c[0]=1	
while 2 not in c:
  g=l[g]-1
  if c[g]==1:
    a=d[g]
    c[g]+=1
    cp=g
  else:
    c[g]+=1
    d[g]=count
    count+=1
    
if k-count<=0:
  kk=d.index(k)
  print(kk+1)
else:
  r=(k-a)%(count-a)
  kk=d.index(a+r)
  print(kk+1)

Submission status: Time Limit Exceeded

Solution code:
N, K = input().split()
AN = input().split()
if 1 in AN:
    K = K - 1
i = 1
N1 = int(AN[0])
NX = AN[N1-1]
while i < int(K):
    NX = AN[N1-1]
    N1 = int(NX)
    i += 1
print(NX)

Submission status: Time Limit Exceeded

Solution code:
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
  reduced = (K - count1) - (int((K - count1)/count2)*count2)
  for i in range(reduced):
    answer = l[answer - 1]

print(answer)

Submission status: Time Limit Exceeded

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(N):
    ANS = Myfunc(ANS)
    if ANS in visted:
        beANS = (K-visted.index(ANS)) % (len(visted) - visted.index(ANS))
        del visted[:visted.index(ANS)]
        ANS = visted[beANS-1]
        print(ANS+1)
        break
    visted.append(ANS)
    if i +1 == K:
        print(ANS+1)
        break

Submission status: Time Limit Exceeded

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

x=1
l=deque()
l.append(1)
for i in range(k):
    y=a[x-1]
    if y not in l:
        l.append(y)
        x=y
    else:
        x=y
        break

j=l.index(x)
mod=(k-len(l))%(len(l)-j)
for i in range(j):
    l.popleft()
print(l[mod])

Submission status: Time Limit Exceeded

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

t = 1
tl = [1]

flg = False
for i in range(len(a)):
    flg = t > a[t-1]
    t  = a[t-1]
    stl = sorted(tl)
    if flg and t in stl:
        break
    else:
        tl.append(t)

tl2 = tl[tl.index(t):len(tl)]
         
# print(tl)
# print(tl2)

ans = 0

if k <= len(tl):
    ans = tl[k]
else:
    k = k - len(tl)
    j = k % len(tl2)
    ans = tl2[j]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k = (int(x) for x in input().split())
a_list = list(int(x) for x in input().split())
#print(a_list)
g=0
for i in range(k):
    g = a_list[g]-1

print(g+1)

Submission status: Time Limit Exceeded

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

N,K=(int(x) for x in input().rstrip('\n').split())
As = [int(x)-1 for x in input().rstrip('\n').split()]
now=0
pas = [0]
for i in range(N):
  now = As[now]
  pas.append(now)
  if now in pas[:-1]:
    break
arrive = pas.index(now)
loop = len(pas)-arrive-1
if K>arrive:
  K -= arrive
  K = K%loop
  K += arrive
print(pas[K]+1)

Submission status: Time Limit Exceeded

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

now_pos = 1
log_pos = []

while True:
  k= k - 1
  log_pos.append(now_pos)
  now_pos = telepoter[now_pos-1]
  
  if now_pos in log_pos:
    break
  
  if k == 0:
    print(now_pos)
    exit()

log_pos = log_pos[log_pos.index(now_pos):]
print(log_pos[k%len(log_pos)])

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
A = [0]+list(map(int,input().split()))
i = 1
X = []
flag = True
for _ in range(K):
    X.append(i)
    if X.count(i)>1:
        flag=False
        break
    i = A[i]
    
if flag:
    print(i)
else:
    u = X.index(i)
    v = len(X)-1
    y = v - u
    m =  (K-u)%y
    print(X[u+m])

Submission status: Time Limit Exceeded

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

"""
l = 0  
count = 0
for i in range(k) :
    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)    

"""

l = a[0] -1
count = 1

while l != 0 :
    l = a[l] -1
    count += 1

for i in range(k%count) :
    l = a[l]-1 
print(l+1)

Submission status: Time Limit Exceeded

Solution code:

n, k = map(int, input().split(" "))
temp = [1]

a = list(map(int, input().split(" ")))
num = 0
fusoku = False
while(True):
    if a[temp[-1] - 1] in temp:
        num = temp.index(a[temp[-1] - 1])
        break
    temp.append(a[temp[-1] - 1])
    if k < len(temp):
        fusoku = True
        break
if fusoku:
    print(temp[k])
else:
    syuuki = len(temp) - num
    k = (k - num) % syuuki + num
    print(temp[k])

Submission status: Time Limit Exceeded

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):
	if A[pre] in where_li:
		break
	where_li.append(A[pre])
	pre = A[pre]-1

len_w = len(where_li)
mod_s = len_w-where_li.index(A[pre])
if K<=len_w:
	print(where_li[K-1])
else:
	if (K-len_w)%mod_s==0:
		d = mod_s
	else:
		d = (K-len_w)%mod_s
	print(where_li[d-1+where_li.index(A[pre])])

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:

def main():
    n,k = map(int,input().split())
    dests =[0 for _ in range(n)]
    telepos = list(map(int,input().split()))
    for i,t in enumerate(telepos):
        dests[i] = t-1
    print(dfs(dests,k))




def dfs(dests,k,here = 0):
    here = 0
    telepo_times = 0
    cycle_start = -1
    cycle_end = -1
    cycle_length = -1
    visited = []
    ids = dict()


    #循環検出！同じ町にいつ戻ってくるのか
    while telepo_times < k:
        #print("現在地は",here)
        if here in visited:
            cycle_start = ids[here]
            #print(cycle_start,"でループが始まった")
            cycle_end = telepo_times - 1
            #print(cycle_end,"でループが終わった")
            cycle_length = cycle_end - cycle_start + 1
            #print("サイクルの長さは",cycle_length,"だ")
            break
        ids[here] = telepo_times

        visited.append(here)
        telepo_times += 1
        here = dests[here]
    if cycle_length == -1:
        return here + 1

    cycle_index = (k-cycle_start) % cycle_length
    return visited[cycle_start + cycle_index] + 1




    #telepo_times = 0
    #while telepo_times < (k - cycle_start)%cycle_length:
    #    telepo_times += 1
    #    here = dests[here]







if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

n,k = map(int,input().split())
l = list(map(int,input().split()))
memo1 = [0]*(n+1)
memo2 = []
tmp = 0
t = 1
index = 0

for _ in range(n):
    tmp = l[t-1]
    if memo1[t-1] != tmp:
        memo1[t-1] = tmp
        memo2.append(tmp)
        t = tmp 
    else:
        memo2.append(tmp)
        indexes = [i for i, x in enumerate(memo2) if x == memo1[t-1]]
        index = indexes[1] - indexes[0]
        exit

tmp2 = k - indexes[1]
if tmp2 <= 0:
    print(memo2[k-1])
else:
    tmp2 = tmp2%index
    if tmp2 == 0:
        print(memo1[indexes[0]])
    else:
        print(memo2[indexes[0]+tmp2-1])

Submission status: Time Limit Exceeded

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

a = [0]
a.extend(list(map(int, input().split())))
a1 = []
for i in range(0, len(a)):
    a1.append(0)
step = 1
t = 0
if k<=8:
    for i in range(0, k):
        step = a[step]
    print(step)
else:

    for i in range(0, 7):
        step = a[step]

        step1 = step
    while(True):
        t += 1
        step1 = a[step1]
        if step1 == step:
            break
    result = step
    k = (k-7) % t
    for i in range(0, k):
        result = a[result]

    print(result)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

def main():

    input = stdin.readline

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

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

    itta_list = []
    idou_num = 0

    pos = 0

    for i in range(K):
        # itta_list記憶
        if pos not in itta_list:
            itta_list.append(pos)
        else:
            idou_num = i
            break

        # 次の街へ
        pos = A[pos] - 1
    else:
        ans_num = pos + 1
        print(ans_num)
        return

    roop_list = itta_list[itta_list.index(pos):]

    amari = (K - idou_num) % len(roop_list)

    ans_pos = roop_list[amari] + 1

    print(ans_pos)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
N, K = map(int, input().split())
a = list(map(int, input().split()))
cnt = 0
li = [1]
c = 1
for i in range(200001):
    cnt += 1
    c = a[c-1]
    if cnt == K:
        print(c)
        sys.exit()
    if c in li:
        break
    li.append(c) 
b = li[li.index(c):]
e = (K-cnt)%len(b)
print(b[e])

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
list = list(map(int,input().split()))
a = 1
list2=[]
begin = 0
time = 0
flag=False
while flag==False:
    a = list[a-1]
    for i,x in enumerate(list2):
        if x == a:
            begin=i
            time = len(list2)-begin
            flag=True
    list2.append(a)
list3 = list2[begin:begin+time]
if K<=begin:
    print(list2[K-1])
else:
    print(list3[(K-begin)%time-1])

Submission status: Time Limit Exceeded

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

num = K
memo = []
town = 1
if K > N:
    for _ in range(K):
        memo.append(town)
        if not A[town-1] in memo:
            town = A[town-1]
            num -= 1
        else:
            index = memo.index(A[town-1])
            l = len(memo) - index
            if num % l == 0:
                town = memo[-1]
            else:
                town = memo[index + (num % l) - 1]
            break
else:
    for _ in range(K):
        town = A[town - 1]

print(town)

Submission status: Time Limit Exceeded

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

V = 1
for _ in range(K):
    V = T[V-1]
print(V)

Submission status: Time Limit Exceeded

Solution code:
n, k = [int(x) for x in input().strip().split()]
a = [int(x) for x in input().strip().split()]
assert len(a) == n
a = [0] + a
current = 1
way = [1]
for i in range(k):
  current = a[current]
  if current in way:
    li = way.index(current)
    loop = way[li:]
    print(loop[(k - li) % len(loop)])
    break
  else:
    way.append(current)
else:
  print(current)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

#ループを探す？

checked_list = [1]
que = deque([a[0]])


counter = 0
while True:
    counter += 1
    x = que.popleft()
    if counter == k:
        print(x)
        exit()
    if x in checked_list:
        startflg = checked_list.index(x)
        loop_length = counter - startflg
        loop_list = checked_list[startflg:counter]
        amari = (k-startflg) % loop_length
        print(loop_list[amari])
        exit()
    else:
        que.append(a[x-1])
        checked_list.append(x)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

ans = 0
for i,_ in enumerate(range(k)):
    if i == 0:
        ans = num_list[ans]
    else:
        ans = num_list[ans-1]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int, input().split())
d={}
l = list(map(int, input().split()))
for i in range(len(l)):
    d[i+1] = l[i]

city = 1
l2 = [1]
while True:
    city = d[city]
    if city in l2:
        break
    l2.append(city)
first = l2.index(city)
if len(l2) <= k:
    if city == l2[-1]:
        print(city)
    else:
        l2 = l2[first:]
        print(l2[(k-first)%(len(l2))])
else:
    print(l2[k])

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

# まずループを見つけてみる

loopstart = -1
loopend = -1
path = []
nextcity = 0
for i in range(N):
    currentcity = nextcity
    path.append(nextcity)
    nextcity = A[nextcity]-1
    if nextcity in path:
        loopstart = nextcity
        loopend = currentcity
        path.append(nextcity)
        break
#print(path)

# ループまでの距離
toloop = path.index(loopstart)

# ループ内の距離
looplength = path.index(loopend) - toloop + 1

#print(toloop)
#print(looplength)
if K < toloop + looplength + 1:
    print(path[K] + 1)
else:
    fromloopstart = (K - toloop) % looplength
    print(path[toloop + fromloopstart] + 1)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
As = list(map(int,input().split()))
route = [0]
pre = 0
i = 0
len_route = 1
for k in range(K):
    i = As[i]-1
    if i in route:
        pre = route.index(i)
        route = route[pre:]
        len_route -= pre
        break
    route.append(i)
    len_route += 1
# print(route)
mod = len_route
print(route[(K-pre)%mod]+1)

Submission status: Time Limit Exceeded

Solution code:

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

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

former = 1
has_come = [0] * n

def fun():
    global former
    for i in range(k):
        next_town = tele[former - 1]
        if next_town in has_come:
            return i
        has_come[i] = next_town
        former = next_town
    else:
        print(former)
        return None

rtn = fun()
if rtn is not None:
    loop_start = tele[former - 1]
    loop_start_idx = has_come.index(loop_start)

    last_tele = k - rtn
    loop = has_come[loop_start_idx:rtn]
    print(loop[last_tele % len(loop) - 1])

Submission status: Time Limit Exceeded

Solution code:
input_nk = list(map(int,input().split(" ")))

input_Alist = list(map(int,input().split(" ")))

next_teleport =1
i = 1
while i <= input_nk[1]:
    now = next_teleport-1
    next_teleport = input_Alist[now]
    i+= 1
print(next_teleport)

Submission status: Time Limit Exceeded

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

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

here = 1
towns = []
while(True):
  towns.append(here)
  next_town = A[here-1]
  here = next_town
  if next_town in set(towns):
    towns.append(next_town)
    break;

start = towns.index(towns[-1])
    
if k <= start:
  print(towns[k])
else:
  idx = (k - start) % (len(towns)-1-start) + start
  print(towns[idx])

Submission status: Time Limit Exceeded

Solution code:
n,k = list(map(int,input().split()))
A = list(map(int,input().split()))
tour=[0]
next_town = 0
for i in range(n*2):
    next_town=A[next_town]-1
    if next_town in tour:
        first_roop_idx = tour.index(next_town)
        break
    tour.append(next_town)
#print(tour)
if k<=len(tour):
    ans = tour[k]
else:
    k-=first_roop_idx
    #print(k)
    k=k%(len(tour)-first_roop_idx)
    #print(k)
    ans = tour[first_roop_idx+k]
print(ans+1)

Submission status: Time Limit Exceeded

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

know = []
now = 1
cnt = 0
while 1:
    if now in know: break
    know.append(now)
    now = a[now]

start = a[know[-1]]
for i,num in enumerate(know):
    if num == start: loop = know[i:] ; break

#print(know,start,loop)

cnt = len(loop)
if k>=len(know):
    k -= len(know)
    ans = loop[k%cnt]

else:
    ans = know[k]

print(ans)

Submission status: Time Limit Exceeded

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)
        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: Time Limit Exceeded

Solution code:
import numpy as np
N, K = map(int, input().split())


A_list = list(map(int, input().split()))
A_list = np.array(A_list) - 1
#A_list = [A - 1 for A in A_list]

path = [0]
town = 0
k = K
j = 0
while k > 0:
  town = A_list[town]
                     
  if town in path:
    #print("town is {}".format(town))
    #print("path is {}".format(path))
    first_visit = path.index(town)
    loop_size = j - first_visit + 1
    #print("loop_size is {}".format(loop_size))
    #print("k is {}".format(k))
    k = (k-1) % loop_size 
    #print("k is now {}".format(k))
    town = path[first_visit + k]
    break
    
  path.append(town)
    
  k = k - 1
  j = j + 1

print(town+1)

Submission status: Time Limit Exceeded

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

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

if k <= l:
  print(C[k])

else:
  o = C.index(a)
  p = l - o
  m = (k-o)%p + o
  print(C[m])

Submission status: Time Limit Exceeded

Solution code:
N,K=input().split()
N=int(N)
K=int(K)
A=list(map(int, input().split()))
i=1
a=[1]
d=A[0]
if (2<=N<=2*10**5)and(1<=K<=10**18):
    a.append(A[0])
    while True:
        d=A[d-1]
        if d in a:
            i+=1
            break
        a.append(d)
        i+=1
    e=a.index(d)
    f=len(a)
    g=f-e
    if K<=e:
        print(a[K])
    if K>e:
        K=K-e
        h=K%g
        h=e+h
        print(a[h])

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
from collections import defaultdict

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

for f, t in enumerate(A):
    to_next[f+1] = t

route = [1]
current_node = 1
loop_index = [-1, -1]

for idx, _ in enumerate(range(N+2)):
    route.append(to_next[current_node])
    current_node = route[-1]
    if idx+1 == K:
        print(route[-1])
        exit(0)
    if len(set(route)) != idx+2:
        loop_index[0] = route.index(current_node)
        loop_index[1] = idx
        break

if loop_index[0] != 0:
    K = K - loop_index[0]
ans_idx = K % (loop_index[1] - loop_index[0] + 1)

print(route[loop_index[0]:loop_index[1]+1][ans_idx])

Submission status: Time Limit Exceeded

Solution code:
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
# print([a-1 for a in A])
L = [-1 for i in range(N)]
visited = []
now = 0
loopstarts = None
looplength = None
for i in range(N):
    if now in visited:
        break
    else:
        L[now] = i
        visited.append(now)
        now = A[now]-1
# print(visited, L, now)
loopstarts = visited.index(now)
looplength = len(visited)-loopstarts
# print(loopstarts)
# print(looplength)
if K < loopstarts:
    print(visited[K]+1)
else:
    print(visited[loopstarts+(K-loopstarts)%looplength]+1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

def main():
    n, k = map(int, stdin.readline().rstrip().split())
    a = [int(x)-1 for x in stdin.readline().rstrip().split()]
    n = a[0]
    his = [-1, n]
    f = his.append
    while True:
        n = a[n]
        if n in his:
            f(n)
            break
        f(n)
    idx = his.index(his[-1])
    loop = len(his[his.index(his[-1]):-1])
    if len(his) > k:
        print(his[k]+1)
    else:
        t = (k - idx) % loop
        g = his[idx:-1]
        print(g[t]+1)
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n, k = map(int, input().split())
a = (0,) + tuple(map(int, input().split()))

c = deque()
i = 1
while True:
    A = a[i]
    if A in c:
        break
    else:
        c.append(a[i])
        i = A

c = list(c)
s = c.index(A)

if k < s:
    print(c[k-1])
else:
    k -= s
    c = c[s:]
    ans = c[k % len(c) - 1]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import logging

logging.basicConfig(level=logging.INFO, format="%(message)s")
#logging.disable(logging.CRITICAL)


def main():
    N, K = map(int, input().split())
    A_i = list(map(int, input().split()))
    B_i = []
    cycle_list = []
    
    cycle = 0
    diff = 0
    counter = 0
    machi = 1
    while True:
        if machi in B_i:
            diff = B_i.index(machi)
            cycle = counter - diff
            cycle_list = B_i[diff:]
            break
        else:
            counter += 1
            machi = A_i[machi - 1]

    mod_K = (K - diff) % cycle

    print(cycle_list[mod_K])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
t = [1]
i = -1
while True:
    a = A[t[-1]-1]
    if a in t:
        i = t.index(a)
        break
    t.append(a)
if K < len(t):
    print(t[K])
else:
    K -= len(t)
    K %= len(t[i:])
    print(t[i+K])

Submission status: Time Limit Exceeded

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

a=input().split()

l=len(a)

for i in range(0,l):
    a[i]=int(a[i])

p=1
h=[]
go=0
for i in range(1,k+1):
    
    
    
    

    h.append(p)
    p=a[p-1]
    
    if p in h:
        j=h.index(p)
        amari=(k-i-1)%(i-j)
        p=h[j+amari]
        go=1
        break

if go==1:
    p=a[p-1]

print(p)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
havebeen=[]
current=1
for i in range(k):
  current=a[current-1]
  if current not in set(havebeen):
    havebeen+=[current]
  else:
    break
if i==k-1:
  print(current)
else:
  nokori=k-1-i
  havebeen=[current]
  for j in range(nokori):
    current=a[current-1]
    if current not in set(havebeen):
      havebeen+=[current]
    else:
      break
  if j==nokori-1:
    print(current)
  else:
    print(havebeen[nokori%len(havebeen)])

Submission status: Time Limit Exceeded

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

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

count = [0]
Check = [0] * N
while True:
    countCheck = copy.copy(count)
    count.append(A[count[-1]]-1)
    if(Check[count[-1] == 1]):
        break

    Check[count[-1]] += 1
#    print(countCheck, count)

#print(count)


saisyo = count.index(count[-1]) + 1

loop_kazu = len(count) - saisyo

#print(loop_kazu)
K_loop = K - saisyo

ans_index = K_loop % loop_kazu
#print(ans_index)

ans = count[saisyo + ans_index] + 1

print(ans)

#hoge = count[loop:loop_kaisuu]
#ans = hoge[(K - loop) % loop_kaisuu]

#ans = count[K % loop] + 1

#print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
#print(a)
#dist =[0]*n
d2 = []
cur = 1
d2.append(1)
st_idx = 0
rp_lgt = 0
for i in range(n):
  cur = a[cur-1]
  #dist[i] = cur
  #print(cur)
  for j in range(len(d2)):
    if cur == d2[j] :
      st_idx = j - 1 
      rp_lgt = i - j + 1
      #print(cur)
      break
  d2.append(cur)
wk = k - st_idx
md = wk % rp_lgt
if k < st_idx:
  ans = d2[k]
else:
  ans = d2[md+st_idx]
print(ans)

Submission status: Time Limit Exceeded

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-visted.index(ANS)) % (len(visted) - visted.index(ANS))
        del visted[:visted.index(ANS)]
        ANS = visted[beANS-1]
        print(ANS+1)
        break
    visted.append(ANS)
    if i +1 == K:
        print(ANS+1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
n, k = map(int, input().split())

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

loop_dict = {}

loop_dict[0] = 1
next_a = 1
start = k+1
for i, a in enumerate(a_list, 1):
    next_a = a_list[next_a - 1]

    tmp = [
        k
        for k, v
        in loop_dict.items()
        if v == next_a
    ]
    if len(tmp) == 1:
        start = tmp[0]
        end = len(loop_dict) - 1
        diff = end - start
        break

    loop_dict[i] = next_a

if k < start:
    print(loop_dict[k])
else:
    k -= start
    mod = k % (diff + 1)
    print(loop_dict[mod+start])

Submission status: Time Limit Exceeded

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
#

if n < k:
  while 1:
    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(lst[(k+div[0]-div[1])%div[0]]+1)
else:
  for i in range(k):
    t = a[t]
  print(t+1)
#
#print(div)
#print(lst)

Submission status: Time Limit Exceeded

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

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

here = 1
towns = []
while(True):
  towns.append(here)
  next_town = A[here-1]
  here = next_town
  if next_town in set(towns):
    towns.append(next_town)
    break;

loop = len(towns) - towns.index(towns[-1])

if k <= towns.index(towns[-1]):
  print(towns[k])
else:
  idx = (k - towns.index(towns[-1])) % (len(towns)-1-towns.index(towns[-1])) + towns.index(towns[-1])
  print(towns[idx])

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
town = 1
number = [1]
l = list(map(int, input().split()))
for i in range(k):
    town -= 1
    town = l[town]
    if town == l[town-1]:
        break
    if town in number:
        hit = number.index(town)
        waru = i - hit + 1
        naka = (k - hit) % waru
        town = number[hit + naka]
        break
    number.append(town)
print(town)

Submission status: Time Limit Exceeded

Solution code:
import sys

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

i = 1
l = [1] * N
n = 1
while True:
    n = A[n-1]
    if n in l:
        l = l[:i]
        mod = i - l.index(n)
        init_len = l.index(n)
        break
    else:
        l[i] = n
        i += 1

if K < init_len:
    print(l[K])
else:
    rest = ((K-init_len) % mod)
    print(l[init_len+rest])

Submission status: Time Limit Exceeded

Solution code:
n, k = list(map(int,input().split()))
a = list(map(int,input().split()))
 
position = 1
exp = [1]
count = 0
 
if n >= k:
  for i in range(k):
    position = a[position - 1]
  print(position)
else:
  for i in range(k):
    position = a[position - 1]
    count += 1
    if not position in exp:
      exp.append(position)
    else:
      break
  init = exp.index(position)
  res = (k - init) % (count - init)
  print(exp[init + res])

Submission status: Time Limit Exceeded

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

pos = -1
seen = [False] * n
hist = []
cycle = []
i = 0
while(seen[i] == False):
    seen[i] = True
    hist.insert(0, i)
    ne = a[i]-1
    i = ne
    if (seen[i] == True):
        pos = i

preCircle = len(hist)

cnt = 0
while(len(hist) != 0):
    b = hist[0]
    cycle.append(b)
    cnt += 1
    hist.pop(0)
    if (b == pos):
        break

preCircle -= cnt

cycle = list(reversed(cycle))

if (k < preCircle):
    print(hist[-k-1] + 1)
else:
    k -= preCircle
    ans = k % len(cycle)
    print(cycle[ans] + 1)

Submission status: Time Limit Exceeded

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

#行ったことある町リスト
d=[1]
i=0
while i<K:
  T=A[d[-1]-1]
  if T in d:
    break
  d.append(T)
  i+=1
F=d.index(T)
LOOP_TOWN=d[d.index(T):len(d)]
q=(K-F)%len(LOOP_TOWN)
print(LOOP_TOWN[q])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

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

visited = deque()
i = 0
cnt = 0
while True:
    if cnt == k:
        print(i+1)
        sys.exit()
    if i in visited:
        break
    visited.append(i)
    i = a[i]
    cnt += 1

si = visited.index(i)
loop = list(visited)[si:]
n_loop = len(loop)
left_k = k - cnt
print(loop[left_k % n_loop] + 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import sys
sys.setrecursionlimit(4100000)

n,m= map(int,readline().split())
a = list(map(int,readline().split()))

if a[0] == 1:
  print(1)
  exit()
  
d = [0]
def dfs(now,cc,d):
    if cc == m:
      return now
    else:
      next = a[now]
      next -= 1
      if not next in d:
        d.append(next)
        return dfs(next,cc+1,d)
      else:
        for i,di in enumerate(d[::-1]):
          if di == next:
            return (i+1,cc,now)

def f(now,cc):
    global mar
    if cc == mar:
      return now
    else:
      next = a[now]
      next -= 1
      return f(next,cc+1)
    
res = dfs(0,0,d)
if type(res) == int:
  print(res+1)
else:
  m -= res[1]
  mar = m % res[0]
  print(f(res[2],0)+1)

Submission status: Time Limit Exceeded

Solution code:
def main():
    # 町の数N, 町iの転送先はindexがAi-1の町
    N,K = map(int, input().split())
    A = list(map(int, input().split()))

    # K回移動した時の町番号を出力
    # もし一度出てきた番号が出てきたら記憶している道順リストを使う
    # 最初は道を覚えさせる作業が必要
    now = 0
    history = [0]
    i = 0
    while i<K:
        # まず進む
        now = A[now]-1
        # 道順登録
        if now not in history:
            history.append(now)
            i+=1
        # 以前出てきてる町ならそこから末尾までを自動で進めてiのカウントも進める
        else:
            # 末尾未満
            skip = len(history)-history.index(now)-1
            now = history[history.index(now)+skip]
            i += skip

    print(now+1)

main()

Submission status: Time Limit Exceeded

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

loop = [1]

while sorted(loop) == sorted(list(set(loop))):
  loop.append(alist[loop[-1]-1])
  
a = loop[:-1].index(loop[-1])
b = len(loop)-1-a

if k <= a:
  print(loop[k])
else:
  print(loop[(k-a)%b+a])

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = [1,a[0]]
sircle=[]
not_sircle = []
i = 0
while True:
    i=a[i]-1
    b.append(a[i])
    if a[i] in b[0:-1]:
        not_sircle = b[0:b.index(a[i])]
        sircle = b[b.index(a[i]):-1]
        break
mod = (k-len(not_sircle))%len(sircle)
if len(not_sircle)>k:
    print(not_sircle[k])
else:
    print(sircle[mod])