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()) 
A = [int(i)-1 for i in input().split()]
now = 0

while K:
    if K % 2: 
        now = A[now]
    tmp = A[:]
    for i in range(N):
        tmp[i] = A[A[i]]
    A = tmp[:]
    K //= 2
print(now + 1)

Submission status: Time Limit Exceeded

Solution code:
def isInt(x):
    try:
        float(x)
    except ValueError:
        return False
    else:
        return float(x).is_integer()

def main():
    try:
        str = input().split()
    except ValueError:
        return

    if isInt(str[0]):
        N = int(str[0])
    else:
        return

    if not( 2 <= N and N <= 2*10**5):
        return

    if isInt(str[1]):
        K = int(str[1])
    else:
        return

    if not( 1 <= K and K <= 10**18):
        return

    try:
        str = input().split()
    except ValueError:
        return

    A = [0] * N
    for i in range(N):
        if isInt(str[i]):
            ai = int(str[i])
            if 1 <= ai and ai <= N:
                A[i] = ai
            else:
                return
        else:
            return
        
    now = 1
    for i in range(K):
        now = A[now-1]

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

Submission status: Time Limit Exceeded

Solution code:
def isInt(x):
    try:
        float(x)
    except ValueError:
        return False
    else:
        return float(x).is_integer()

def main():
    try:
        str = input().split()
    except ValueError:
        return

    if isInt(str[0]):
        N = int(str[0])
    else:
        return

    if not( 2 <= N and N <= 2*10**5):
        return

    if isInt(str[1]):
        K = int(str[1])
    else:
        return

    if not( 1 <= K and K <= 10**18):
        return

    try:
        str = input().split()
    except ValueError:
        return

    A = []
    for i in range(N):
        if isInt(str[i]) and 1 <= int(str[i]) and int(str[i]) <= N:
            A.append(int(str[i]))
        else:
            return
    now = 1
    for i in range(K):
        now = A[now-1]

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

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
A=  list(map(int,input().split()))
now = 0
if K <= N:
    for i in range(K):
        now = A[now]-1
    print(now+1)
else:
    alr = [0]
    now = 0
    for i in range(K):
        now = A[now]-1
        if now not in alr:
            alr.append(now)
        else:
            loop = alr[alr.index(now):]
            rem = K - i - 1
            break
    ans = loop[rem%len(loop)]+1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
change = list(input().split())
town = 1
j = 1
for i in range(k):
    j = int(town) - 1
    town = change[j]
print(town)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split()) #N = 4,K=5
A = [int(i)-1 for i in input().split()]
log_K = K.bit_length() #3bit (5 = 101)
next = [[-1]*N for _ in range(log_K)]

for i in range(N):
    next[0][i] = A[i]
    
for k in range(log_K - 1):
    for i in range(N):
        next[k+1][i] = next[k][next[k][i]]  

now = 0
for i in range(log_K)[::-1]: 
    if ((K >> i) & 1) == 1: 
        now = next[i][now]
print(now + 1)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
list = list(map(int, input().split()))
val = list[0]
startcnt = 1
roopList = []
roopList.append(1)
while True:
    roopList.append(val)
    val = list[val - 1]
    startcnt += 1
    if val in roopList:
        break
roopCount = len(roopList) - roopList.index(val)
if k <= startcnt:
    print(roopList[k])
else:
    roopList = roopList[roopList.index(val):]   
    print(roopList[(k - startcnt) % roopCount])

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
where_go = list(map(int, input().split()))
now = 0
PATH = []
start = 0
roop = 0
count = 0

while now not in PATH and count < K:
    PATH.append(now)
    now = where_go[now] -  1
    count += 1

if count < K:
    start = PATH.index(now)
    roop = len(PATH) - start
    K = (K - start) % roop
    count = 0
    while count < K:
        now = where_go[now] -  1
        count += 1

print(now+1)

Submission status: Time Limit Exceeded

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

l = [A[0]]
a = A[0] - 1
for _ in range(K):
    if A[a] not in l:
        l.append(A[a])
        a = A[a] - 1
    else:
        a = A[a]
        break
n = len(l)
b = 0
for i in range(n):
    if l[i] == a:
        del l[0:i]
        b = i
        break
T = len(l)
S = (K - b) % T
ans = l[S - 1]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,K,*A=map(int,open(0).read().split())
a=1
while K>0:
 if K&1:a=A[a-1]
 A=[A[A[i]-1] for i in range(N)]
 K>>=1
print(a)

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, K, *A = map(int, open(0).read().split())
    log_k = 0
    k = K
    while k > 0:
        k >>= 1
        log_k += 1
    # print(log_k)
    work = [[0]*N for i in range(log_k)]
    # level 1
    for i in range(N):
        work[0][i] = A[i]
    for k in range(log_k - 1):
        for i in range(N):
            work[k + 1][i] = work[k][work[k][i] - 1]
    ans = 1
    k = K
    level = 0
    # print(work)
    while k > 0:
        if k & 1 == 1:
            ans = work[level][ans - 1]
        level += 1
        k >>= 1
    print(ans)

def main1():
    N, K, *A = map(int, open(0).read().split())
    visited = [-1]*N
    pos = A[0]
    visited[0] = 0
    visited[pos - 1] = 1
    step = 2
    order = 0
    start = 0
    step_to_start = 0
    while True:
        pos = A[pos - 1]
        if visited[pos - 1] == -1:
            visited[pos - 1] = step
        else:
            step_to_start = visited[pos - 1]
            order = step - step_to_start
            start = pos
            break
        step += 1
    # print(start, step_to_start, order)

    if K <= step_to_start:
        ans = 1
        for i in range(K):
            ans = A[ans - 1]
        print(ans)
        return
    remain = (K - step_to_start) % order
    ans = start
    for i in range(remain):
        ans = A[ans - 1]
    print(ans)

if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
list = []
i = 0
j = 0
while i not in list and j < K:
    list.append(i)
    i = X[i] - 1
    j += 1

if K == j:
    print(i+1)

else:    
    loop = j - list.index(i)
    print(list[(K - list.index(i)) % loop + list.index(i)]+1)

Submission status: Time Limit Exceeded

Solution code:
from math import log2
from collections import deque
n, k = map(int, input().split())
To = deque([])
A = list(map(int, input().split()))
A = list(map(lambda x: x - 1, A))
To.append(A)
for i in range(int(log2(k))):
    N = [0 for i in range(n)]
    for j in range(n):
        N[j] = To[i][To[i][j]]
    To.append(N)

v = 0
for i in reversed(range(int(log2(k)) + 1)):
    l = 1 << i
    if l <= k:
        v = To[i][v]
        k -= l
    else:
        pass

print(v + 1)

Submission status: Time Limit Exceeded

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

next = [[0]*n for _ in range(60)]
for i in range(n):
    next[0][i] = al[i]-1

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

res = 0
for p in range(59,-1,-1):
    if (k>>p)&1 == 1:
        res = next[p][res]

print(res+1)

Submission status: Time Limit Exceeded

Solution code:
import math
import numpy as np

def Next(): return input()
def NextInt(): return int(Next())
def NextInts(): return map(int,input().split())
def Nexts(): return map(str,input().split())
def NextIntList(): return list(map(int,input().split()))
def RowInts(n): return [input() for i in range(n)]

n,k = NextInts()
da = np.array(NextIntList(), np.int64)
for i in range(n):
    da[i]-=1

dp = np.zeros((61, n), dtype=np.int64)

dp[0] = da

for i in range(60):
    for j in range(n):
        dp[i+1][j] = dp[i][dp[i][j]]

ans = 0
for i in range(61):
    if k&1:
        ans = dp[i][ans]
    k >>= 1
print(ans+1)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,(input().split()))
A=list(map(int,input().split()))
A.insert(0,0)
loc=1
log=[0]
loop_flg=0
i=1
while(i<=K):
  if(loc not in log):
    log.append(loc)
  elif(loc in log and loop_flg==0):
    logind=log.index(loc)
    loop_longth=i-logind
    K = i+((K-logind)%loop_longth)
    loop_flg=1
  loc=A[loc]
  i+=1
print(loc)

Submission status: Time Limit Exceeded

Solution code:
from math import log2
n, k = map(int, input().split())
To = []
A = list(map(int, input().split()))
A = list(map(lambda x: x - 1, A))
To.append(A)
for i in range(int(log2(k))):
    N = [0 for i in range(n)]
    for j in range(n):
        N[j] = To[i][To[i][j]]
    To.append(N)

v = 0
for i in reversed(range(int(log2(k)) + 1)):
    l = 1 << i
    if l <= k:
        v = To[i][v]
        k -= l
    else:
        pass

print(v + 1)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,(input().split()))
A=list(map(int,input().split()))
A.insert(0,0)
loc=1
log=[0]
loop_flg=0
i=1
while(i<=K):
  if(loc not in log):
    log.append(loc)
  elif(loc in log and loop_flg==0):
    loop_longth=i-log.index(loc)
    K = i+((K-log.index(loc))%loop_longth)
    loop_flg=1

  loc=A[loc]
  i+=1
print(loc)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
a=[[0]*n for _ in range(100)]
A=list(map(int,input().split()))
for i,j in enumerate(A):
    a[0][i]=j-1
i=1
while 2**i<k:
    for x,y in enumerate(a[i-1]):
        a[i][x]=a[i-1][y]
    i+=1
x=0
for j in range(i):
    if k>>j&1:
        x=a[j][x]
print(x+1)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int, input().split())
A = [int(i) for i in input().split()]
p = 1
p_hist = []
p_hist_index = [-1] * (N+1)
while p not in p_hist:
    p_hist_index[p] = len(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]
if K < start_loop_idx:
    print(p_hist[K])
else:
    print(p_hist[(K-start_loop_idx)%(end_loop_idx-start_loop_idx+1)+start_loop_idx])

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
ls,ans=[],[]
be,count,cnt=0,0,0

for i in range(n):
  ls.append(a[be])
  be=ls[-1]-1
  
  if len(ls)!=len(set(ls)):
    
    for i in range(len(ls)):
      
      if ls[i]==ls[-1]:
        
        if cnt==2:
          break
          
        cnt+=1
        ans.append(ls[i])
        
        
          
        continue
        
      if cnt==1:
        ans.append(ls[i])
        continue
        
     # print("W",i)
      count+=1
    break

del ans[-1]

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

Submission status: Time Limit Exceeded

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

m = 60

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

D = [A]
for i in range(m):
  temp = []
  for j in range(N):
    temp.append(D[i][D[i][j]])
  D.append(temp)

now = 0
for i in range(m):
  if K >> i&1 == 1:
    now = D[i][now]
print(now+1)

Submission status: Time Limit Exceeded

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

m = 60
L = pow(2,m)

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

D = [A]
for i in range(m):
  temp = []
  for j in range(N):
    temp.append(D[i][D[i][j]])
  D.append(temp)

now = 0
for i in range(m):
  if K >> i&1 == 1:
    now = D[i][now]
print(now+1)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
roop = 0
port = [A[0]]
 
for _ in range(N):
    port.append(A[port[-1]-1] )
    if port.count(A[port[-2]-1]) == 2:#A in port
        port.pop()
        roop = len(port)-port.index(A[port[-1]-1])
        break
if len(A)>=K:
    print(port[K-1])
else:
    Kroop = K-len(port)-1
    print(port[len(port)-roop+(Kroop%roop)])

Submission status: Time Limit Exceeded

Solution code:
#167
#d
n,k = map(int, input().split())
ln = list(map(int, input().split()))# まちi にいるとき次に町ln[i-1]へいく

# n,k = 10*4,10**18
# ln = list(range(2,n+1))
# ln.append(1)

visit = [0]*n 
now= 1
visit[0] =1
before =[1]
while max(visit) <= 1:
    now = ln[now -1]
    before.append(now)
    visit[now-1] += 1
roops = before.index(now)
roop_ln = before[roops:-1]
mae = before[:roops]
if k <len(mae):
    print(mae[k])
elif len(mae) <= k :
    t = k- len(mae)
    print(roop_ln[t%len(roop_ln)])

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    n, k = map(int, input().split())
    d = 60
    to = [[0]*(n) for _ in range(d)]
    to[0] = list(map(lambda x: int(x) - 1, input().split()))
    for i in range(d-1):
        for j in range(n):
            to[i+1][j] = to[i][to[i][j]]
    
    v = 0
    for i in range(d, -1 , -1):
        l = pow(2, i)
        if l <= k:
            v = to[i][v]
            k -= l
    print(v+1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

for _ in range(len(A)):
    port.append(A[port[-1]-1] )
    if port.count(A[port[-2]-1]) == 2:#A in port
        port.pop()
        roop = len(port)-port.index(A[port[-1]-1])
        break
if len(A)>=K:
    print(port[K-1])
else:
    Kroop = K-len(port)-1
    print(port[len(port)-roop+(Kroop%roop)])

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
a_preorder=[1]
for i in range(n):
    a_preorder.append(a[a_preorder[i]-1])
a_order=[]
a_first=[]
a_cycle=[]
for i in range(n):
    if(a_preorder[i] in a_order):
        index=a_order.index(a_preorder[i])
        a_first=a_preorder[0:index+1]
        a_order.append(a_preorder[i])
        a_cycle=a_preorder[index+1:i+1]
        break
    else:
        a_order.append(a_preorder[i])
if(len(a_cycle)==0):
    a_cycle=a_first
a_first_len=len(a_first)
a_cycle_len=len(a_cycle)
if(k<=a_first_len):
    print(a_first[k])
else:
    restcycle=k-a_first_len
    num=restcycle%a_cycle_len
    print(a_cycle[num])

Submission status: Time Limit Exceeded

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

place = [0]

while True:
    next_place = A_list[place[-1]] - 1
    if next_place in place:
        idx = place.index(next_place)
        loop = place[idx:]
        break
    place.append(next_place)

if K < len(place):
    print(place[K] + 1)
else:
    print(loop[(K-idx)%len(loop)] + 1)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int, input().split())
A = list(map(int, input().split()))
C=[]
for i in range(N):
    C.append([i+1,A[i]])
s=1
s=C[s-1][1]
counter=1
while s!=1:
    s=C[s-1][1]
    counter+=1
y=K%counter
s=1
for i in range(y):
    s=C[s-1][1]
print(s)

Submission status: Time Limit Exceeded

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

print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy

def main():
  input = sys.stdin.readline
  n, k = map(int, input().split())
  a = [int(x)-1 for x in input().split()]
  key = [copy.deepcopy(a) for _ in range(61)]
  for i in range(60):
    for j in range(n):
      key[i+1][j] = key[i][key[i][j]]
  
  i = 0
  now = 0
  while k > 0:
    if k%2:
      now = key[i][now]
    k //= 2
    i += 1
  
  print(now+1)
  
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N, K = map(int, input().split())
A = list(map(int, input().split()))
 
klog = 60
t = np.zeros(shape=(N, klog+1), dtype=np.int)

t[:, 0] = A
for i in range(klog):
    ti = list(map(lambda x: t[x-1, i], t[:, i]))
    t[:, i+1] = ti

c = bin(K)[2:]
a = [len(c) - int(i) for i, b in enumerate(c) if b == '1']

j = 1
for i in a:
    j = t[j-1, i-1]

print(j)

Submission status: Time Limit Exceeded

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

  d = 60
  to = [[0] * N for _ in range(d)]

  for i in range(N):
    #テレポート距離が2^0のデータを入れる
    #これは入力A1〜ANと同じ
    to[0][i] = A[i] - 1 #0-indexedにする

  for i in range(1, d):
    for j in range(N):
      to[i][j] = to[i-1][to[i-1][j]]

  v = 0
  for i in range(d-1, -1, -1):
    l = 1 << i

    if(K >= l):
      v = to[i][v]
      K -= l

  print(v + 1)

if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

a = [int(i) - 1  for i in input().split()]

l = [a[0]]
j = a[0]
for i in range(1,k):
    j = a[j]
    if j in l:
        break
    else:
        l.append(j)
        
m = l.index(j) 

length = len(l) - m
l = l[m:]

l = {idx + 1:i for idx,i in enumerate(l)}
l[0] = l[length]
del l[length]

m = (k - m) % length

print(l[m] + 1)

Submission status: Time Limit Exceeded

Solution code:
Num1 = list(map(int,input().split()))
N = Num1[0]
K = Num1[1]
Num2 = list(map(int,input().split()))
i = 0
j = 1
while i < K:
  j = Num2[j-1]
  i += 1
print(j)

Submission status: Time Limit Exceeded

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

A=list(map(int,input().split()))
TP=[1]
now=1
next=1
for k in range(N):
    next=A[now-1]
    TP.append(next)
    now=next
#6回未満なら、法則性考える必要なし
#print(TP)
if K<=N:
    print(TP[K])
#6回以上⇒パターン考慮
else :
    Lstart=0
    for i in range(1,N+1):
        if TP.count(i) > 1:
            Lstart=i
            break
    startnum=0
    nextnum=0
    startnum=TP.index(Lstart)
    nextnum=TP.index(Lstart,startnum+1,len(TP)-1)
    Lstep=nextnum-startnum
#    print(K,startnum,nextnum,Lstep)
    where=(K-startnum)%Lstep
    print(TP[where+startnum])

Submission status: Time Limit Exceeded

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

A=list(map(int,input().split()))
TP=[1]
now=1
next=1
for k in range(N):
    next=A[now-1]
    TP.append(next)
    now=next
#6回未満なら、法則性考える必要なし
#print(TP)
if K<=N:
    print(TP[K])
#6回以上⇒パターン考慮
else :
    Lstart=0
    for i in range(1,N+1):
        if TP.count(i) > 1:
            Lstart=i
            break
    startnum=0
    nextnum=0
    count=0
    for i in range(0,N+1):
        if TP[i]==Lstart:
            if count==0:
                startnum=i
                count=1
            elif count==1:
                nextnum=i
                break
    Lstep=nextnum-startnum
    #print(K,startnum,nextnum,Lstep)
    where=(K-startnum)%Lstep
    print(TP[where+startnum])

Submission status: Time Limit Exceeded

Solution code:
class Doubling:
    m = 0
    to = [[]]
    # fを次の値を得る関数として、[0,n)のvについて最大でf^k(v)を得られる。
    def __init__(self, n, f, k):
        while k > 0:
            k = k >> 1
            self.m += 1
        self.to = [[-1] * n for _ in range(self.m+1)]
        for j in range(n):
            self.to[0][j] = f(j)
        for i in range(self.m):
            for j in range(n):
                if self.to[i][j] == -1:
                    self.to[i+1][j] = -1
                else:
                    self.to[i+1][j] = self.to[i][self.to[i][j]]

    # p番目の値のq個先を得る。
    def query(self, p, q):
        for i in range(self.m+1):
            if p == -1:
                break
            if (q >> i) & 1:
                p = self.to[i][p]
        return p

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

d = Doubling(n, lambda x: a[x]-1, k)
print(d.query(0, k) + 1)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
t=list(map(int,input().split()))
g=[1]
h=[0]
for i in range(N):
  if t[g[i]-1] in set(g):
    a=i+1
    h[0]=t[g[i]-1]
    break
  g.append(t[g[i]-1])
if K>a:
  for i in range(N):
    if t[h[i]-1] in set(h):
      break
    h.append(t[h[i]-1])
  b=i+1
  K=(K-a)%b+a-b
print(g[K])

Submission status: Time Limit Exceeded

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


# nowから2**i先まで移動したとこ
def double(now, i):
    global A
    if A[i][now] != -1:
        return A[i][now]
    # nowから2**(i-1)移動して、そこからさらに2**(i-1)移動する
    A[i][now] = double(double(now, i - 1), i - 1)
    return A[i][now]


# nowからk移動した場所を求める
def rec(now, k):
    if k == 0:
        return now
    # if k == 1:
    #     return A[now]

    log2k = len(bin(k)) - 3
    return rec(double(now, log2k), k - 2 ** log2k)

print(rec(1, K))

Submission status: Time Limit Exceeded

Solution code:
import collections
import numpy as np
import sys
import copy

N,K=map(int,input().split())
A=list(map(int,input().split()))
for i in range(N):
    A[i]-=1
B=[0]
C=[]
Flag=True
for i in range(0,N*2):
    B.append(A[B[i]])
    if len(B)%2==0:
        for j in range(len(B)//2):
            u=B[-j - 1:]
            v=B[(-j-1)*2:-j-1]
            if u==v:
                C=list(B[-j-1:])
                Flag=False
                num=len(B)-2*len(C)
    if not Flag:
        break
#print(C)
Ans=(K-num)%len(C)
print(C[Ans]+1)

Submission status: Time Limit Exceeded

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

D = 60 #10**18は60桁なので2の59乗まで見る
MAX_N = 200005 #頂点番号
to = [[0 for _ in range(MAX_N)] for _ in range(D)]

#to[i][j]:jから2^i個先の頂点
for i in range(n):
    to[0][i] = A[i]
    to[0][i] -= 1

#ダブリングの表
for i in range(D-1):
    for j in range(n):
        to[i+1][j] = to[i][to[i][j]]

v = 0
for i in range(D-1, -1, -1):
    l = 1<<i #2^i個先を見る
    if l <= k:
        v = to[i][v]
        k -= l

print(v+1)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
a=list(map(int, input().split()))
 
town=0
x=[]
for i in range(n):
    town=a[town]-1
    x.append(town+1)
 
s=[1]
for y in x:
    if y in s:
        last=y
        break
    s.append(y)
    
for i, t in enumerate(s):
    if t==last:
        index=i
  
if k<len(s):
    print(s[k])
else:
    kk=k-len(s)
    ss=s[index:]
    print(ss[kk%len(ss)])

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
A = list(map(int, input().split()))
c = 1
P = [1]
for i in range(1,k+1):
    c = A[c-1]
    if i == k:
        print(c)
        exit(0)
    if c in P:
        roop_start = P.index(c)
        roop_num = i- roop_start
        a = (k - roop_start) %  roop_num
        b = P[a + roop_start]
        print(b)
        exit(0)
    P.append(c)

Submission status: Time Limit Exceeded

Solution code:
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+1)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
A = list(map(int, input().split()))
c = 1
P = [1]
for i in range(1,k+1):
    c = A[c-1]
    if c in P:
        roop_start = P.index(c)
        roop_num = i- roop_start
        break
    P.append(c)
    if i == k:
        roop_start = '8'
        roop_num = 'b'
if roop_start == '8':
    a = k
    roop_start = 0
else:
    a = (k - roop_start) %  roop_num
b = P[a + roop_start]
print(b)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N, K = [int(item) for item in input().split()]
    A_list = [int(item) for item in input().split()]

    bit_k = bin(K)[2:]

    telepo_list = collections.deque([A_list])

    for _ in range(len(bit_k)-1):
        temp_list = telepo_list[-1]
        new_telep = collections.deque([])
        for i in temp_list:
            new_telep.append(temp_list[i-1])

        telepo_list.append(new_telep)

    # print(telepo_list)

    goto = 1
    for i in range(len(bit_k)):
        temp_list = telepo_list.popleft()
        if ((K >> i) & 1): 
            goto = temp_list[goto -1]
            # print(i, goto)

    print(goto)

if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N, K = [int(item) for item in input().split()]
    A_list = [int(item) for item in input().split()]

    bit_k = bin(K)[2:]

    telepo_list = [A_list]

    for _ in range(len(bit_k)-1):
        temp_list = telepo_list[-1]
        new_telep = []
        for i in temp_list:
            new_telep.append(temp_list[i-1])

        telepo_list.append(new_telep)

    # print(telepo_list)

    goto = 1
    for i in range(len(bit_k)):
        temp_list = telepo_list[i]
        if ((K >> i) & 1): 
            goto = temp_list[goto -1]
            # print(i, goto)

    print(goto)

if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

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

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

for i in range(N):
    A[i] -= 1

b = bin(K)
D = {0:list(range(N))} # ダブリングマトリクス
D[1] = [A[D[0][i]] for i in range(N)]

for i in range(1, len(b)-2):
    D[2**i] = [D[2**(i-1)][D[2**(i-1)][j]] for j in range(N)]


n = 2**(len(b[2:])-1)
S = D[n][0] # 初期状態
keta = len(b[2:]) - 2
for j in range(len(b[3:])):
    k = 2**keta
    if b[j+3] == '1':
        S = D[k][S]
    keta -= 1

print(S+1)

Submission status: Time Limit Exceeded

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

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

for i in range(N):
    A[i] -= 1

b = bin(K)
D = {0:list(range(N))} # ダブリングマトリクス
d = []
for i in range(N):
    d.append(A[D[0][i]])
D[1] = d


for i in range(1, len(b)-2):
    d = []
    for j in range(N):
        d.append(D[2**(i-1)][D[2**(i-1)][j]])
    D[2**i] = d


n = 2**(len(b[2:])-1)
S = D[n][0] # 初期状態
keta = len(b[2:]) - 2
for j in range(len(b[3:])):
    k = 2**keta
    if b[j+3] == '1':
        S = D[k][S]
    keta -= 1

print(S+1)

Submission status: Time Limit Exceeded

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

dic = {}
for key, a in zip(range(1, n+1), list(map(int,input().split()))):
    dic[key] = a
 
keynum = 0
log = [1]
next = dic[1]
log.append(next)
k -= 1
while k:
    next = dic[next]
    if next in log:
        keynum = log.index(next)
        k -= 1
        break
    log.append(next)
    k -= 1
looplen = len(log[keynum:])
if k < len(log[keynum:]):
    print(log[-1])
else:
    res = k%looplen
    print(log[keynum+res])

Submission status: Time Limit Exceeded

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

start = 0
end = 0
pointer = 1

for i in range(n+1):
    pointer = a[pointer]
    if pointer in b:
        start = b.index(pointer)
        end = i
        break
    b.append(pointer)


# print(b,start,end)

if k <= len(b):
    print(b[k])
else:
    print(b[(k-start)%(end-start+1) + start])

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
t=list(map(int,input().split()))
g=[1]
for i in range(N):
  if t[g[i]-1] in set(g):
    h=g.index(t[g[i]-1])
    s=i+1-h
    break
  g.append(t[g[i]-1])
if K>h:
  K=(K-h)%s+h
print(g[K])

Submission status: Time Limit Exceeded

Solution code:
#English veery bad
n,k=map(int,input().split())
town=list(map(int,input().split()))
def f(x):
  return town[x-1]
if k<n:#first process the except pattern
  x=1
  for i in range(k):
    x=f(x)
  print(x)
  exit()
li=[1]+[0]*(n-1) #the list of towns already have arrived
x=1
CNT=0
while li.count(2)==0:
  x=f(x)
  li[x-1]+=1
  CNT+=1
#at this point x is the start of loop 
#count how much it takes until we get to x at the first time
#CNT is the length until the first loop ends
s=1
cnt=0
while s!=x:
  s=f(s)
  cnt+=1
#cnt is the first time when we get to "x" i.e. starting loop
loop=CNT-cnt #loop's length
p=(k+1-cnt)%(loop) 
if p!=0:#usually
  p=p+cnt-1 #moving p times get the same answer with moving k times
  x=1
  for i in range(p):
    x=f(x)
  print(x)
else:#when the loop ends just at that time 
  p=loop+cnt-1
  x=1
  for i in range(p):
    x=f(x)
  print(x)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
sub = [0]*n
ans = 1
cir = 0
a = 0
b = 0
if k < n:
  for i in range(k+1):
    sub[i] = ans
    ans = A[ans-1]
  print(sub[k])
else:
  for i in range(n):
    sub[i] = ans
    b = A[ans-1]
    if b in sub:
      a = sub.index(b)
      cir = i+1 - a
      break
    else:
      ans = b
  print(sub[a + (k - a) % cir])

Submission status: Time Limit Exceeded

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

start = 0
end = 0
pointer = 1

for i in range(n+1):
    pointer = a[pointer]
    if pointer in b:
        for j in range(len(b)):
            if pointer == b[j]:
                start = j
                break
        end = i
        break
    b.append(pointer)


# print(b,start,end)

if k <= len(b):
    print(b[k])
else:
    print(b[(k-start)%(end-start+1) + start])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

import sys

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

    nw = 1
    lp0 = [1]
    for i in range(N):
        nw = A[nw-1]
        if nw in lp0:
            break
        else:
            lp0.append(nw)
    lpc = i+1 - lp0.index(nw)
    lp = lp0[-lpc:]

    if K<=len(lp0)-1:
        print(lp0[K])
    else:
        K-= len(lp0)-1
        K=K%lpc - 1
        print(lp[K])

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

import sys

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

    nw = 1
    lp0 = [1]
    for i in range(N):
        nw = A[nw-1]
        if nw in lp0:
            break
        else:
            lp0.append(nw)
    lpc = i+1 - lp0.index(nw)
    lp = lp0[-lpc:]

    if K<=len(lp0)-1:
        print(lp0[K])
    else:
        K-= len(lp0)-1
        K=K%lpc - 1
        print(lp[K])

if __name__ == '__main__':
    main()