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: Runtime Error

Solution code:
num,time = input().split(" ")
_map_str =  input().split(" ")
_map_ref = {}
_map_index = {}
num = int(num)
time = int(time)

_index = 0
next_index = 0
re_cal = False
while _index < time:
    if _map_ref.get(next_index,None) == None:
        _map_ref[next_index] = 0

    if _map_index.get(next_index,None) == None:
        _map_index[next_index] = _map_str[next_index]

    if _map_ref[next_index] + 1 == 3:
        re_cal = True
        break
    _map_ref[next_index] = _map_ref[next_index] + 1
    _index = _index + 1
    next_index = _map_str[int(next_index)] - 1

num1,num2 = 0,0
for k,v in _map_ref.items():
    if v == 2:
        num2 = num2 + 1
    elif v == 1:
        num1 = num1 + 1

if re_cal:
    time = (time - num1) % num2 + num1
    print(_map_index[time])
else:
    print(_map_str[int(next_index) - 1])

Submission status: Runtime Error

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


flag = ['.']*(n+1)
flag[1] = 'v'

been = [1]

for i in range(k):
    goto = alist[been[-1]-1]
    if flag[goto] == '.':
        been.append(goto)
        flag[goto] = 'v'
    else:
        loopstart = goto
        break
loop = been[been.index(loopstart):]

print(loop[(k+1-loopstart)%(len(loop)+been.index(loopstart))])

Submission status: Runtime Error

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


flag = ['.']*(n+1)
flag[1] = 'v'

been = [1]

for i in range(k):
    goto = alist[been[-1]-1]
    if flag[goto] == '.':
        been.append(goto)
        flag[goto] = 'v'
    else:
        loopstart = goto
        break
loop = been[been.index(loopstart):]
print(loop[(k-loopstart)%len(loop)])

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
count = 0
ans = 0
inf = float("inf")

n,k=I()
a = l()
move = []
move.append(a[0])
i = a[0]-1
while count != n:
    if a[i] in move:
        y = move.index(a[i])
        count = y
        move = move[y:]
        break
    else:
        move.append(a[i])
        i = a[i]-1

na = len(move)
ama = k%na
print(move[ama-y-1])

Submission status: Runtime Error

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

move = 1
l = [1]
flag = [False]*(N+1)
flag[1] = True

for i in range(K):
    move = A[move-1]
    if flag[move]:
        ind = l.index(move)
        l = l[ind:]
        break
    flag[move] = True
    l.append(move)

rest = (K-ind) % (len(l))

print(l[rest])

Submission status: Runtime Error

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

now=1
bn[1]=0
for i in range(1, k+1):
    print(bn)
    now = an[now-1]
    if bn[now] >0:
        rp =i-bn[now]
        p= (k-i)%rp
        for j in range(p):
            now = an[now-1]
        print(now)
        exit(0)
    bn[now]=i
print(now)

Submission status: Runtime Error

Solution code:
#D
from collections import deque
n,k = map(int,input().split())
a = list(map(int,input().split()))
tel = deque()
tel.append(1)
visit = [False for _ in range(n)]
visit[0] = True
for i in range(n):
    nx = a[tel[i]-1]
    if visit[nx-1] == True :
        tel.append(nx)
        #ループの始まりのindexをidxに格納
        idx = tel.index(nx)
        break
    tel.append(nx)
    visit[nx-1] == True
    
#print(tel)
if k - idx <=0:
    print(tel[k-1])
else:
    k -= idx
    loop_num = len(tel) - idx - 1
    #print('idx:',idx)
    #print('loop_num:',loop_num)
    goal = tel[idx + k%loop_num]
    
    print(goal)

Submission status: Runtime Error

Solution code:
#####################################################################################################
##### 深さ優先探索 幅優先探索　（グラフ）
#####################################################################################################

'''

キューに頂点を入れる回数は各々高々１回のみ。
各辺を使う回数は高々一回のみ（辺を戻るような探索は枝切りされている）
結果として、計算量はO(N + M)

'''

import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
from copy import deepcopy



class Graph:
    def __init__(self, n, dictated=False, decrement=True, edge=[]):
        self.n = n
        self.dictated = dictated
        self.decrement = decrement
        self.edge = [set() for _ in range(self.n)]
        self.parent = [-1]*self.n
        self.info = [-1]*self.n
        for x, y in edge:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edge[x].add(y)
        if self.dictated == False:
            self.edge[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edge[i] = set(map(lambda x:x-1, adjacent_list))
        else:
            self.edge[i] = set(adjacent_list)

    def cycle_detector(self, start, time=0, save=False):
        """
        :param p: スタート地点
        :param save: True = 前回の探索結果を保持する
        :return: 各点までの距離と何番目に発見したかを返す
        """

        edge2 = deepcopy(self.edge)

        if self.decrement:
            start -= 1
        if not save:
            self.parent = [-1] * self.n

        p, t = start, time
        self.parent[p] = -2
        cycle_end = False
        cycle_time = 0
        cycle = []
        while True:
            if edge2[p]:
                q = edge2[p].pop()
                if q == self.parent[p]:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if self.parent[q] != -1:
                    """ サイクルで同一点を訪れた時の処理 """
                    if not cycle:
                        cycle.append(q + self.decrement)
                        cycle.append(p + self.decrement)
                        cycle_time = t
                    """"""""""""""""""""
                    continue
                self.parent[q] = p
                p, t = q, t + 1
            else:
                """ 探索完了時の処理 """
                """"""""""""""""""""
                if p == start and t == time:
                    break
                p, t = self.parent[p], t-1
                """ 二度目に訪問時の処理 """
                if cycle and t == cycle_time - 1 and not cycle_end:
                    if cycle[0] == p + self.decrement:
                        cycle_end = True
                        continue
                    cycle.append(p + self.decrement)
                    cycle_time = t

                """"""""""""""""""""
        cycle = list(reversed(cycle))
        return [cycle[-1]] + cycle[:-1]

    def tree_counter(self, detail=False):
        """
        :param detail: True = サイクルのリストを返す
        :return: 木（閉路を含まない）の個数を返す
        """
        self.parent = [-1] * self.n

        connection_number = 0
        cycle_list = []

        for p in range(self.n):
            if self.parent[p] == -1:
                connection_number += 1
                cycle = self.cycle_detector(p + self.decrement, save=True)
                if cycle:
                    cycle_list.append(cycle)
        if not detail:
            return connection_number - len(cycle_list)
        else:
            return cycle_list

    def draw(self):
        """
        :return: グラフを可視化
        """
        import matplotlib.pyplot as plt
        import networkx as nx

        if self.dictated:
            G = nx.DiGraph()
        else:
            G = nx.Graph()
        for x in range(self.n):
            for y in self.edge[x]:
                G.add_edge(x + self.decrement, y + self.decrement)

        nx.draw_networkx(G)
        plt.show()

##################################################################


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

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


M = N
graph = Graph(N,dictated=True)
for i in range(1,M+1):
    x = i
    y = A[i-1]
    graph.add_edge(x, y)

p = 0
cnt = 0
if K <= N:
    while cnt + 1 <= K:
        p = A[p] - 1
        cnt += 1
    res = p + 1
else:
    cycle = list(graph.cycle_detector(1))
    len_cycle = len(cycle)
    p = 0
    cnt = 0
    res = 0
    while p != cycle[0] - 1:
        p = A[p] - 1
        cnt += 1
    k = (K - cnt) % len_cycle
    res = cycle[k]
print(res)

Submission status: Runtime Error

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

now = 1
visited = []
visited_set = set()
for i in range(1, K+1):
    visited.append(now)
    visited_set.add(now)
    now = A[now]
    if now in visited_set:
        loop_start = visited.index(now)
        loop_length = i - loop_start
        break

print(visited[loop_start + (K - loop_start) % loop_length])

Submission status: Runtime Error

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

now = 1
visited = []
for i in range(1, K+1):
    visited.append(now)
    now = A[now]
    if now in visited:
        loop_start = visited.index(now)
        loop_length = i - loop_start
        break

print(visited[loop_start + (K - loop_start) % loop_length])

Submission status: Runtime Error

Solution code:
#####################################################################################################
##### 深さ優先探索 幅優先探索　（グラフ）
#####################################################################################################

'''

キューに頂点を入れる回数は各々高々１回のみ。
各辺を使う回数は高々一回のみ（辺を戻るような探索は枝切りされている）
結果として、計算量はO(N + M)

'''

from collections import deque
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline



def bfs(conj, start, goal=None, visit=set()):
    visit.add(start)                            # スタート地点はすでに訪れている
    next_set = deque([(start, 0)])              # 次に進む候補を列挙する。スタック（右から取り出す = pop）だと深さ優先になり、キュー（左から取り出す = popleft）だと幅優先になる
                                                # 第一成分はスタート地点、第二成分は時刻を表す。
    while next_set:                             # p = [] になったら止める
        p, t = next_set.popleft()               # 要素を消去して、消去した要素を出力
        for q in conj[p]:                       # 頂点 p から進める経路の候補から一つ選ぶ
            if q in visit:                      # 一度訪れていた場合は進まない
                continue
            if q == goal:                       # ゴールがあるならば、ここで判定
                return t + 1                    # 経路の長さは t + 1 で与えられる
            visit.add(q)                        # 頂点 q に一度訪れた事をメモ (for の前に書くと、ここで選ばれた q が最短であるはずなのに、違う経路でvisit = Trueを踏んでしまう可能性がある)
            next_set.append((q, t + 1))         # p から q へと移動。時刻を 1 進める
    return -1


def connection_counter(conj):                   # conj の連結成分の個数を返す。関数 bfs が必要
    cnt = 0
    visit = set()
    for start in range(N):
            if start not in visit:
                cnt += 1
                bfs(start, conj, visit)
    return cnt


def distance_list(conj, start, visit=set()):    # スタート地点からの距離の全列挙
    dist = [0]*N
    visit.add(start)
    next_set = deque([(start, 0)])
    while next_set:
        p, t = next_set.popleft()
        for q in conj[p]:
            if q in visit:
                continue
            dist[q] = t+1
            visit.add(q)
            next_set.append((q, t + 1))
    return dist


def dfs(conj, start, goal=None, visit=set()):
    visit.add(start)                            # スタート地点はすでに訪れている
    next_set = [(start, 0)]                     # 次に進む候補を列挙する。スタック（右から取り出す = pop）だと深さ優先になり、キュー（左から取り出す = popleft）だと幅優先になる
                                                # 第一成分はスタート地点、第二成分は時刻を表す。
    while next_set:                             # p = [] になったら止める
        p, t = next_set.pop()                   # 要素を消去して、消去した要素を出力
        for q in conj[p]:                       # 頂点 p から進める経路の候補から一つ選ぶ
            if q in visit:                      # 一度訪れていた場合は進まない
                continue
            if q == goal:                       # ゴールがあるならば、ここで判定
                return t + 1                    # 経路の長さは t + 1 で与えられるる
            visit.add(q)                        # 頂点 q に一度訪れた事をメモ (for の前に書くと、ここで選ばれた q が最短であるはずなのに、違う経路でvisit = Trueを踏んでしまう可能性がある)
            next_set.append((q, t + 1))         # p から q へと移動。時刻を 1 進める
    return -1

#############################################################
# キャッシュにメモしながら動的計画法を行う場合など、
# 帰りがけ時に子ノードたちの結果をまとめるような処理が重要な場合には、
# 再帰関数を用いた DFS が簡明 (メモ化再帰)。
#############################################################


def dfs2(conj, p=0, goal=None, t=0, past_p=None, visit=set(), second_visit=set()):
    # global res
    visit.add(p)
    for q in conj[p]:
        if q == past_p:
            # 逆流した際の処理
            continue
        if q in second_visit:
            # 帰り道に訪れた際の処理
            continue
        if q in visit:
            continue
        if q == goal:
            # ゴール時の処理
            # return t+1
            continue
        # p から q への引継ぎ処理
        # res[q] += res[p]
        dfs2(conj, q, goal, t+1, p, visit, second_visit)
    second_visit.add(p)
    # 帰り際の処置（壊した道を元に戻す等)
    # visit.discard(p)
    return # res


def cycle_detector(conj, p=0, t=0, past_p=None, path=[], visit=set(), second_visit=set(), cycle=[]):
    visit.add(p)
    path.append(p)
    for q in sorted(conj[p]):
        if q == past_p:
            continue
        if q in second_visit:
            continue
        if q in visit:
            if not cycle:
                while path:
                    r = path.pop()
                    cycle.append(r)
                    if r == q:
                        break
            continue
        cycle_detector(conj, q, t+1, p, path, visit, second_visit,cycle)
    second_visit.add(p)
    return cycle


def tree_counter(conj, detail=False):           # 木（閉路を含まない）の個数を返す。detail = True で、閉路のリストを返す
    connection_number = 0
    cycle_list = []
    visit = set()
    second_visit = set()
    for start in range(N):
        if start not in visit:
            connection_number += 1
            cycle = cycle_detector(conj, start, visit=visit, second_visit=second_visit, cycle=[])
            if cycle:
                cycle_list.append(cycle)
    if not detail:
        return connection_number - len(cycle_list)
    else:
        return cycle_list


def path_detector(conj, p=0, t=0, past_p=None, full_path=[], visit=set(), second_visit=set(), decrement=False):   # 距離と探索経路を返す。デクリメントされている場合は、decrement=True にする
    visit.add(p)
    full_path.append((p + decrement,t))
    for q in sorted(conj[p]):
        if q == past_p:
            continue
        if q in second_visit:
            continue
        if q in visit:
            continue
        path_detector(conj, q, t+1, p, full_path, visit, second_visit, decrement)
    second_visit.add(p)
    full_path.append((p + decrement,t))
    return full_path

##################################################################

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

conj = [set() for _ in range(N)]
for i in range(M):
    u = i
    v = A[i] - 1
    conj[u].add(v)
    conj[v].add(u)                            # 無効グラフの場合は消す


cycle = list(reversed(cycle_detector(conj, p=0, t=0, past_p=None, path=[], visit=set(), second_visit=set(), cycle=[])))
len_cycle = len(cycle)
p = 0
cnt = 0
while p != cycle[0]:
    p = A[p] - 1
    cnt += 1
k = (K-cnt)%len_cycle
print(cycle[k] + 1)

Submission status: Runtime Error

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

A = [0] + A

visited = [1]
now = 1
short = 0
while True:
  next = A[now]
  if next in visited:
    break
  visited.append(next)
  if len(visited)==K:
    short = 1
    break
  now = next

if short: print(visited[K])
else:
  initial = visited.index(next)
  cycle = len(visited[initial:])
  if K >= cycle:
    residual = (K - initial) % cycle
    print(visited[initial+residual])
  else:
    print(visited[K])

Submission status: Runtime Error

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

A = [0] + A

visited = [1]
now = 1
short = 0
while True:
  next = A[now]
  if next in visited:
    break
  if len(visited)==K:
    short = 1
    break
  visited.append(next)
  now = next

if short: print(visited[K])
else:
  initial = visited.index(next)
  cycle = len(visited[initial:])
  if K >= cycle:
    residual = (K - initial) % cycle
    print(visited[initial+residual])
  else:
    print(visited[K])

Submission status: Runtime Error

Solution code:
def mi(): return map(int,input().split())
def lmi(): return list(map(int,input().split()))
def ii(): return int(input())
def isp(): return input().split()

n,k=mi()
a=lmi()

s=[]
s.append(1)

o=[-1]*(n+1)
o[1]=0
t=0
while a:
  p=a.pop(0)
  s.append(p)
  if o[p]!=-1:
    pp=t-o[p]
    ss=o[p]
    break
  o[p]=t
  t+=1
#print(ss,pp)
#print(s)
if k<ss:
  print(s[k-1])

else:
  ans=k%pp
  print(s[ss+ans+1])

Submission status: Runtime Error

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

now = a[0]
path.append(now)

for i in range(1, k+1):
    now = a[now-1]
    if now in path:
        now = a[a.index(now) + (k-i)%(len(path) - a.index(now) - 1)]
        break
    path.append(now)

print(now)

Submission status: Runtime Error

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

r=[]
h=i=0
while i+1 not in r:
    r.append(i+1)
    if k == h:
        print(i+1)
        sys.exit()
    i = a[i] - 1
    h += 1

r.append(i+1)

p = r.index(r[len(r)-1])
q = len(r)-1-r.index(r[len(r)-1])
r_q = r[p:p+q]


if k+1<p:
    print(r[k])
else:
    j = (k+1-p)%q
    print(r_q[j-1])

Submission status: Runtime Error

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

r=[]
h=-1
i=0
while i+1 not in r:
    r.append(i+1)
    i = a[i]-1
    h += 1
    if k == h:
        print(i+1)
        sys.exit()

r.append(i+1)

p = r.index(r[len(r)-1])
q = len(r)-1-r.index(r[len(r)-1])
r_q = r[p:p+q]


if k+1<p:
    print(r[k])
else:
    j = (k+1-p)%q
    print(r_q[j-1])

Submission status: Runtime Error

Solution code:
import numpy as np
N, M, X = map(int, input().split())
A = []
C = []
for _ in range(N):
    c, *a = map(int, input().split())
    C.append(c)
    A.append(a)
A = np.array(A,dtype=int)
ans = 10 ** 7
for bit in range(2 ** N):
    B = np.zeros(M, dtype=int)
    cost = 0
    for i in range(N):
        if bit & (1<<i):
            B += A[i]
            cost += C[i]
    if np.all(B >= X):
        ans = min(ans, cost)
print(ans if ans < 10**7 else -1)

Submission status: Runtime Error

Solution code:
import sys

def main():
    n, k = map(int, sys.stdin.buffer.readline().split())
    a = [0] + list(map(int, sys.stdin.buffer.readline().split()))

    visited = [0]*(n+1)
    town = 1
    for i in range(k+1):
        town = a[town]
        if visited[town] == 0:
            visited[town] = i
        else:
            print(visited.index( (k - visited[town])%(i + visited[town]) + visited[town] ))
            exit()
    print(town)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys

def main():
    n, k = map(int, sys.stdin.buffer.readline().split())
    a = [0] + list(map(int, sys.stdin.buffer.readline().split()))

    visited = [0]*(n+1)
    town = 1
    for i in range(k+1):
        town = a[town]
        if visited[town] == 0:
            visited[town] = i
        else:
            print(visited.index( (k - visited[town])%(i + visited[town]) + visited[town]))
            exit()
    print(town)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys

def main():
    n, k = map(int, sys.stdin.buffer.readline().split())
    a = [0] + list(map(int, sys.stdin.buffer.readline().split()))

    visited = [0]*(n+1)
    town = 1
    for i in range(1, k+1):
        town = a[town]
        if visited[town] == 0:
            visited[town] = i
        else:
            cyc = (k - visited[town])%(i + visited[town]) + visited[town]
            print(visited.index(cyc))
            exit()
    print(town)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

    towns = [1]
    i = 0
    while a[i] not in towns and len(towns) < k:
        towns.append(a[i])
        i = a[i] - 1
    ti = towns.index(a[i])
    if ti+1 > k:
        print(towns[ti])
    else:
        print(towns[(k - ti)%(len(towns) - ti) + ti])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

    towns = [1]
    i = 0
    while a[i] not in towns:
        towns.append(a[i])
        i = a[i] - 1
    ti = towns.index(a[i]) + 1
    if ti > k:
        print(towns[ti - 1])
    else:
        print(towns[(k - ti)%(len(towns) - ti) + ti])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

before=k
roop=1
cnt={}
nxt=1
mp = []
for i in range(1, k+1):
    mp.append(nxt)
    if nxt not in cnt:
        cnt[nxt] = i
        nxt = a[nxt]
    else:
        roop = i - cnt[nxt]
        before = cnt[nxt]-1
        break
print(mp[before + (k-before)%roop])

Submission status: Runtime Error

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

before=0
roop=0
cnt={}
nxt=1
mp = []
for i in range(1, k+1):
    mp.append(nxt)
    if nxt not in cnt:
        cnt[nxt] = i
        nxt = a[nxt]
    else:
        roop = i - cnt[nxt]
        before = cnt[nxt]-1
        break
    roop=0
if roop == 0:
    print(mp[k])
    exit()
print(mp[before + (k-before)%roop])

Submission status: Runtime Error

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

before=0
roop=0
cnt={}
nxt=1
mp = []
for i in range(1, k+1):
    mp.append(nxt)
    if nxt not in cnt:
        cnt[nxt] = i
        nxt = a[nxt]
    else:
        roop = i - cnt[nxt]
        before = cnt[nxt]-1
        break
    roop=0
    before=0

print(mp[before + (k-before)%roop])

Submission status: Runtime Error

Solution code:
import sys

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
A = [0] + A
town = 1
visited = [0]*(N+1)

for i in range(1, K+1):
    town = A[town]
    if visited[town] == 0:
        visited[town] = i
    else:
        loop = i - visited[town]
        town = (K - visited[town]) % loop + visited[town]
print(town)

Submission status: Runtime Error

Solution code:
import sys

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
past_city = [1]
n = 0

for i in range(K):
    if len(past_city) == len(A) or i == K:
        print(past_city[-1])
        sys.exit()
    if A[past_city[i] - 1] in past_city:
        n = i + 1
        break
    past_city.append(A[past_city[i] - 1])
rem = K % n
print(past_city[rem])

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
L = list(map(int,input().split()))
li = [L[0]]
a = L[0]
s = set()
s.add(a)
i = 0
while i <=20:
    a = L[a-1]
    li.append(a)
    
    if a in s:
        #print(s,a,li)
        break
    i +=1
    s.add(a)
    
pre = li.index(li[-1])
li.pop()
c = li[:pre]
d = li[pre:]
#print(c,d)
print(d[(m-len(c))%len(d)-1])

Submission status: Runtime Error

Solution code:
n,k=[int(i) for i in input().split()]
arr=[int(i) for i in input().split()]
from collections import defaultdict
graph=defaultdict(list)
for i in range(n):
    graph[i+1].append(arr[i])
dist=[0]*(n+1)
visited=[0]*(n+1)
cy=[0]
def dfs(s):
    visited[s]=1
    for i in graph[s]:
        if not visited[i]:
            dist[i]=1+dist[s]
            dfs(i)
        else:
            cy[0]=s

dfs(1)
start=arr[cy[0]-1]
if dist[start]>k:
    reach=1
    while k:
        reach=arr[reach-1]
        k-=1
else:
    reach=start
    len_=dist[cy[0]]-dist[start]+1
    if len_!=0:
        k=(k-dist[start])%len_
        while k:
            reach=arr[reach-1]
            k-=1
print(reach)

Submission status: Runtime Error

Solution code:
n,k=[int(i) for i in input().split()]
arr=[int(i) for i in input().split()]
from collections import defaultdict
graph=defaultdict(list)
for i in range(n):
    graph[i+1].append(arr[i])
dist=[0]*(n+1)
visited=[0]*(n+1)
cy=[0]
def dfs(s):
    visited[s]=1
    for i in graph[s]:
        if not visited[i]:
            dist[i]=1+dist[s]
            dfs(i)
        else:
            cy[0]=s

dfs(1)
start=arr[cy[0]-1]
if dist[start]>k:
    reach=1
    while k:
        reach=arr[reach-1]
        k-=1
else:
    reach=start
    len_=dist[cy[0]]-dist[start]+1
    k=(k-dist[start])%len_
    while k:
        reach=arr[reach-1]
        k-=1
print(reach)

Submission status: Runtime Error

Solution code:
import sys
import time

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

queue = {}

start = -1
count = 1

now_town = 1

for i in range(N):
    if town_list[now_town - 1] in queue:
        start = town_list[now_town - 1]
        break
    queue[town_list[now_town - 1]] = count
    now_town = town_list[now_town - 1]
    count += 1

if start == -1:
    print(queue[now_town])
    sys.exit()

before_len = len(queue) - queue[start] - 1
roop = len(queue) - before_len

print(list(queue.keys())[(K - before_len) % roop + before_len - 1])

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
A = [0]+list(map(int,input().split()))
dp = [False]*(N+1)
tele = 0
for i in range(10**5):
    if i==0:
        tele = 1
        dp[tele]=True
    else:
        tele = A[tele]
        if dp[tele]==True:
            finish = i
            tele1 = tele
            break
        else:
            dp[tele]=True
#print(finish)
#print(tele)
tele = 0
for i in range(10**5):
    if i == 0:
        tele = 1
        if tele == tele1:
            start = i
            break
    else:
        tele = A[tele]
        if tele == tele1:
            start = i
            break
#print(start)
loop = finish-start
if K<=start:
    ans = 1
    for i in range(K):
        ans = A[ans]
    print(ans)
else:
    ans = 1
    for i in range(start+(K-start)%loop):
        ans = A[ans]
    print(ans)

Submission status: Runtime Error

Solution code:
import sys

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

roop = 0
queue = [1]

start = -1

for now_town in queue:
    if not town_list[now_town - 1] in queue:
        queue.append(town_list[now_town - 1])

    # 循環した
    else:
        start = town_list[now_town - 1]
        break

if start == -1:
    print(queue[K])
    sys.exit()

before_len = queue.index(start)
roop = len(queue) - before_len

print(queue[before_len + (K - before_len) % roop])

Submission status: Runtime Error

Solution code:
import sys

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

graph = {}
for index, value in enumerate(input().split()):
    graph[index + 1] = int(value)

queue = [1]
now_pos = 1
start = 0

for i in range(K):
    if not graph[now_pos] in queue:
        queue.append(graph[now_pos])
        now_pos = graph[now_pos]

    # 循環した
    else:
        start = graph[now_pos]
        break

before = queue[:queue.index(start)]
roop = queue[queue.index(start):]

for i in range(len(roop)):
    if (K - len(before)) % len(roop) == i:
        print(roop[i])
        sys.exit()

Submission status: Runtime Error

Solution code:
import sys

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

graph = list(map(int, input().split()))
graph.insert(0, 0)

queue = [1]
now_pos = 1
start = 0

for i in range(K):
    if not graph[now_pos] in queue:
        queue.append(graph[now_pos])
        now_pos = graph[now_pos]

    # 循環した
    else:
        start = graph[now_pos]
        break

before = queue[:queue.index(start)]
roop = queue[queue.index(start):]

for i in range(len(roop)):
    if (K - len(before)) % len(roop) == i:
        print(roop[i])
        sys.exit()

Submission status: Runtime Error

Solution code:
import sys

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

graph_seed = list(map(int, input().split()))
graph = {}

for index, route in enumerate(graph_seed):
    index += 1
    graph[index] = route

queue = [1]
now_pos = 1

start = 0

for i in range(K):
    if not graph[now_pos] in queue:
        queue.append(graph[now_pos])
        now_pos = graph[now_pos]

    # 循環した
    else:
        start = graph[now_pos]
        break

before = queue[:queue.index(start)]
roop = queue[queue.index(start):]

for i in range(len(roop)):
    if (K - len(before)) % len(roop) == i:
        print(roop[i])
        sys.exit()

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
B = [1]
a = 0
i = 0
while a == 0:
  i = A[i] - 1
  if (i + 1) in B:
    b = B.index(i + 1)
    C = B[:b]
    D = B[b:]
    a = 1
  else:
    B.append(i + 1)
  
c = len(C)
d = len(D)
if K <= c:
  ans = C[K]
else:
  ans = D[(K - c) % d]
print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
A = [0]+list(map(int,input().split()))
dp = [False]*(N+1)
tele = 0
# 同じものが出てきた時
for i in range(10**5):
    if i == 0:
        tele = 1
        dp[1] = True
    else:
        tele = A[tele]
        if dp[tele] == False:
            dp[tele] = True
        else:
            finish = i
            tele1 = tele
            break
tele = 0
# 始めてループの数が現れる時
for i in range(10**5):
    if i == 0:
        tele = 1
        if tele == tele1:
            start = i
            break
    else:
        tele = A[tele]
        if tele == tele1:
            start = i
            break
loop = finish-start
if K<start:
    ans = 0
    for i in range(K+1):
        if i==0:
            ans = 1
        else:
            ans = A[ans]
    print(ans)
else:
    ans = 0
    for i in range((K-start)%(finish-start)+1):
        if i == 0:
            ans = tele1
        else:
            ans = A[ans]
    print(ans)