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:
n,k=map(int,input().split())
A=list(map(int,input().split()))
A=list(map(lambda x:x-1,A))

next=0
hoge=[]
zisyo={}
for i in range(k):
    next=A[next]
    if next in zisyo:
        t=next
        break
    else:
        zisyo[next]=1
        hoge.append(next)
hoge_1=[]
hoge_2=[]
for i in range(len(hoge)):
    if hoge[i]==t:
        hoge_1=hoge[:i]
        hoge_2=hoge[i:]

ans=0
if k<=len(hoge_1):
    for i in range(k):
        ans=A[ans]
else:
    k=k-len(hoge_1)-1
    k=k%len(hoge_2)
    ans=hoge_2[0]
    for i in range(k):
        ans=A[ans]


print(ans+1)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = [int(n) for n in input().split()]
dest = []
i = 0
while i < K:
    for j in range(len(dest)):
        if A[dest[-1]-1] == dest[j]:
            move = j
            dest = dest[j:]
            break
    else:
        if i == 0:
            dest.append(1)
        else:
            dest.append(A[dest[-1]-1])
        i += 1
        continue
    break
print(A[dest[(K-move)%(len(dest))-1]-1])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
l=list(map(int,input().split()))
list=[l[0]]
num=0
while True:
  if l[list[num]-1] in list:
    break
  list.append(l[list[num]-1])
  num+=1
y=list.index(l[list[num]-1])
x=len(list)-y
ans=list[y:]
print(ans[(k-y)%x-1]

Submission status: Runtime Error

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


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    # Failed to predict input format
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    city = 1
    visited = {city: 0}
    cycle_len = 1

    for i in range(N):
        city = A[city - 1]
        visited[city] = i
        if visited.get(A[city - 1], False):
            offset = visited[A[city -1]]
            cycle_len = i
            break

    K = (K - offset) % (cycle_len - offset)

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

    print(city)
    
    pass

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
a,b=map(int,input().split())
city=list(map(int,input().split()))
ne=[0]*(3000)
ne[0]=1
for i in range(2999):
    ne[i+1]=city[ne[i]-1]
rpp=[]
nrp=[]
for i in ne[1:1500]:
    if i in ne[1501:3000]:
        rpp.append(i)
for i in ne[0:1500]:
    if i not in ne[1501:3000]:
        nrp.append(i)
if len(nrp)>=b-1:
    print(ne[b])
else:
    print(rpp[((b-len(nrp)-1)%len(rpp))])

Submission status: Runtime Error

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)
print(list2,begin)
list3 = list2[begin:begin+time]
if K<=begin:
    print(list2[K-1])
else:
    print(list3[(K-begin)%time-time-1])

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools

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

  now = 0
  times = 0
  visit =[[0],[0]]

  for _ in range(k):
    times += 1
    now = a[now] - 1
    if now in visit[0]:
      roop = times - visit[1][visit[0].index(now)] #何個の町でループしてるかをroopに代入
      roop_start = visit[1][visit[0].index(now)] #ループが始めった待ちの最初に訪れた時に何回ループしていたかをroop_startに代入
      break
    else:
      visit[0].append(now)
      visit[1].append(times)

  k = (k - roop_start) % roop

  now = 0
  for _ in range(roop_start):
    now = a[now] - 1

  for _ in range(k):
    now = a[now] -1

  print(now+1)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

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

rireki = [0] * (n+1)
curr_c = 1
rireki[1] = 0

no_loop_count = k
loop_cnt = 0

for i in range(n):
    next_c = a_list[curr_c-1]
    # print(i, curr_c, next_c)
    if next_c == 1:
        no_loop_count = 0
        loop_cnt = i + 1
        break
    elif rireki[next_c] == 0:
        rireki[next_c] = i+1
    else:
        # print(next_c)
        no_loop_count = rireki[next_c] -1
        loop_cnt = i - no_loop_count
        break
    curr_c = next_c


if k <= no_loop_count:
    ans = rireki.index(k)
else:
    # print('k',k)
    # print('no', no_loop_count)
    # print('lo', loop_cnt)
    ind = (k-1-no_loop_count)%loop_cnt +1
    rireki_fix = [i-no_loop_count for i in rireki]
    # print(ind, 'ind')
    ans = rireki_fix.index(ind)
    # print(rireki_fix)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
# sys.stdin = open('input.txt')

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

cycle = n + 1
# sub = []
place = 0

for i in range(len(a)):
    place = a[i]
    # sub.append(a[i])
    if place == 0:
        # sub = sub[:-1]
        cycle = i
        break

# print(cycle, sub)
# ans = sub[k%cycle] + 1
ans = 0
for i in range(k%cycle+1):
    ans = a[i] + 1
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
List = list(map(int, input().split()))
Lists = []
Listss = []
a = 1
count = 0
counts = 0
while "a" != Lists:
  a = List[a]
  Lists.append("a")
  count = count+1
while "count" != Listss:
  a = List[a]
  Listss.appened("a")
  counts = counts+1
countss = (K - count) % counts 
for i in range(countss):
  a = List[a]
print(a)

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
a = [int(i) for i in input().split()]
b = [a[0]]
for i in range(n-1):
    b.append(a[b[-1]-1])
    c = b.count(b[i])
    if c != 1:
        break


index_num = [n for n, v in enumerate(b) if v == b[i]]
ans = index_num[0] + 1
e = index_num[1]

f = e - ans+ 1

g = k - ans
h = g % f
print(b[index_num[0]+h])

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
l = []
t = 1
for i in range(n):
    l.append(t)
    k -= 1
    if a[t - 1] in l:
        break
    t = a[t - 1]
i = l.index(a[t - 1]) -1
k = k % (len(l)-i)
print(l[k])

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
A = input().split()
A.insert(0,0)
count = 0
position = 1
nokori = K
B = []

while nokori > 0:
  count += 1
  nokori -= 1
  if (int(A[position]) in B):
    B.append(position)
    C = B[B.index(int(A[position])):]
    repeat = len(C)
    break
  else:
    B.append(int(position))
    position = int(A[position])

x = (K - len(B)) % repeat

print(C[x])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline
from collections import Counter
def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    a = [i - 1 for i in a]
    ac = Counter(a)
    kaiten = [0] * n
    count = 0
    koko = 0
    kaitenkikan = 0
    while k > 0:
        koko = a[koko]
        count += 1
        k -= 1
        if kaiten[koko] > 0:
            kaitenkikan = count - kaiten[koko]
            break
        else:
            kaiten[koko] = count
    k_remain = k % kaitenkikan

    while k_remain > 0:
        koko = a[koko]
        k_remain -= 1

    print(koko + 1)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

n, k = map(int, input().split())
a = [int(x) for x in input().split()]
a.insert(0, 0)
now = a[1]
b = [1]
chk = [0] * (n + 1)
chk[1] = 1

while chk[now] == 0:
    chk[now] = 1
    b.append(now)
    now = a[now]

if now == 1:
    c = b
else:
    c = b[now:]

if k < len(b):
    print(b[k])
else:
    cc = k - (len(b) - len(c))
    print(c[cc % len(c)])

Submission status: Runtime Error

Solution code:
n , k = map(int, input().split())
dic = {}
data = input().split()
for i in range(n):
    dic.setdefault(i+1 , int(data[i]))

# find common
tmp = {}
next_t = dic[1]
for i in range(100):
    if next_t not in tmp :
        tmp.setdefault(next_t,1)
    else:
        tmp[next_t]+=1
    next_t = dic[next_t]

common  = []
has_one = False
for k,v in tmp.items():
    if v!= 1:
        common.append(k)
    else:
        has_one = True

if has_one:
    print(common[k%len(common)])
else:
    print(common[k%len(common)])

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
X = [-1 for j in range(N)]
X[0] = 0
Y = [0]
i = 0
Num = 0
MM = 0
for k in range(1,N):
  i = A[i]-1
  if k == K:
    MM = 1
    P = i
  elif X[i] != -1:
    Num = X[i]
    break
  else:
    X[i] = k
    Y.append(i)
Y = Y[Num:]
B = (K-Num)%len(Y)
if MM == 1:
  print(P+1)
else:
  print(Y[B]+1)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import numpy as np
N, K = map(int, input().split())
A = np.array(list(map(int, input().split())))
A = np.insert(A, 0, 0)

flg = [False for _ in range(N + 1)]
town = []
i = 1
while flg[i] == False:
    town.append(i)
    flg[i] = True
    i = A[i]
else:
    s = i
    to_s = town.index(s)
    loop = len(town) - to_s

if len(town) >= K:
    print(town[K])
else:
    print(town[(K - to_s) % loop + to_s])

Submission status: Runtime Error

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

li = [0]
li.extend(list(map(int, input().split())))
tuita = [0]*(n+1)
cnt = 0
town = 1

def search(town, times):
  if times == 0:
    return town
  newTown = li[town]
  newTimes = times - 1 
  return search(newTown, newTimes)

while True:
  town = li[town]
  cnt += 1
  if tuita[town] == 0:
    tuita[town] = cnt
  else:
    if k < tuita[town]:
      print(search(1, k))
    elif k == tuita[town]:
      print(town)
    else:
      print(search(town, (k - tuita[town]) % (cnt - tuita[town])))
    break

Submission status: Runtime Error

Solution code:
def main():
	n, k = [int(x) for x in input().split(" ")]
	a = [int(x) for x in input().split(" ")]
	d = {}
	pos = 0
	step = 0
	cycle = False
	way = []
	while step < k and cycle == False:
		if pos in d:
			cycle = True
		else:
			d[pos] = step
			way.append(pos)
			pos = a[pos] - 1
			step += 1

	k -= step
	cycle = way[d[pos]:step]
	x = k % len(cycle)
	print(cycle[x] + 1)

main()

Submission status: Runtime Error

Solution code:
def resolve():
    N, K = map(int, input().split())
    A = tuple(map(int, input().split()))
    C = [0]*N
    path = []
    cur = 1
    for i in range(K):
        C[cur-1] += 1
        path.append(cur)
        cur = A[cur-1]
        if C.count(2) >= 1:
            init_c = path.index(cur) + 1
            break
    MOD = (K+1) % (len(path) - 1)
    for i in range(init_c, init_c+MOD+1):
        init_c = A[init_c]
    print(init_c)

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
X = [-1 for j in range(N)]
X[0] = 0
Y = [0]
i = 0
Num = 0
MM = 0
for k in range(1,N):
  i = A[i]-1
  if k == K:
    MM = 1
    P = i
  elif X[i] != -1:
    Num = X[i]
    break
  else:
    X[i] = k
    Y.append(i)
Y = Y[Num:]
B = (K-Num)%len(Y)
if MM = 1:
  print(P+1)
else:
  print(Y[B]+1)

Submission status: Runtime Error

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

n = a[0]
k = a[1]

src = 0
passed = [1]
turn = []

for i in range(k):
  dest = b[src]
  if dest in passed:
    if dest in turn:
      count = len(turn)
      now = i + 1
      break
    else:
      turn.append(dest)
  else:
    passed.append(dest)
  src = dest - 1

rep = (k - now) % count
ans = turn[rep]

print(ans)

Submission status: Runtime Error

Solution code:
def main():
    n, k, *a = map(int, open(0).read().split())
    a = [0] + a
    root = [1]
    now = 1
    count = 0
    roop_start = 0
    while count <= k:
        count += 1
        next = a[now]
        if next in root:
            roop_start = next
            break
        else:
            root.append(next)
            now = next
    else:
        print(now)

    root_end = now
    roop_end_index = count - 1
    roop_start_index = root.index(roop_start)

    left_count = k - count
    items = roop_end_index - roop_start_index + 1

    p, q = divmod(left_count, items)
    index = roop_start_index + q


    print(root[index])



if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

A = deque(map(int, input().split()))
li = []
li.append(1)

next = 0
t=0
rep = False
for i in range(n):
    li.append(A[next])
    next = A[next]-1

    if A[next] in li:
        t = li.index(A[next])
        rep = True
        break


if rep == True:
    tmp = k%len(li[t:]) - len(li[0:t])
    g=li[t:]
    print(g[tmp])
else:
    print(li[k-1])

Submission status: Runtime Error

Solution code:

#include <iostream> 
#include <bits/stdc++.h>

using namespace std; 
#define ll long long 
#define ull unsigned long long 
#define tezz std::ios::sync_with_stdio(false);std::cin.tie(NULL);std::cout.tie(NULL);
#define INT_BITS 32 
ll indexi=0;
vector<ll> a(16);
#define MOD 999983

ll NCR(ll NUMBERXXx,ll KEYXx){
    if(KEYXx>NUMBERXXx) return 0;
    ll res=1;
    for(ll i=1;i<=KEYXx;i++){
        res*=NUMBERXXx-i+1;
        res/=i;
    }
    return res;
}
vector<int> getRepresentation(int N) {
    vector<int> res;
    while (N > 0) {
        res.push_back(N % MOD);
        N /= MOD;
    }
    return res;
}
int binpow(int a, int NUMBERXXx) {
    long long res = 1;
    while (NUMBERXXx > 0) {
        if (NUMBERXXx % 2 != 0) {
            res = (res * a) % MOD;
        }
        a = ((long long)a * a) % MOD;
        NUMBERXXx /= 2;
    }
    return (int)res;
}
long long fact[MOD];
int C(int N, int K) {
    if (K > N) {
        return 0;
    }
    return (((fact[N] * binpow(fact[N - K], MOD - 2)) % MOD) * binpow(fact[K], MOD - 2)) % MOD;
}

void solvexXx(){
    	int NUMBERXXx;
	cin >> NUMBERXXx;
	ll KEYXx;
	cin >> KEYXx;
	int ARRAYSX1[NUMBERXXx];
	int INKEUUARRs1 = 1;
	for(int i=0;i<NUMBERXXx;i++){
		cin >> ARRAYSX1[i];
	}
 
 
	unordered_map<int, int> SETSTRssx;
	SETSTRssx[1] = 1;
	int XXKEYXx = 2;
	ll COUNTEERXXx = 0;
	while(1) {
		INKEUUARRs1 = ARRAYSX1[INKEUUARRs1 - 1];
		if(SETSTRssx.find(INKEUUARRs1) != SETSTRssx.end()) {
			COUNTEERXXx = XXKEYXx - SETSTRssx[INKEUUARRs1];
			break;
		}
		SETSTRssx[INKEUUARRs1] = XXKEYXx++;	
	}
	if (KEYXx > SETSTRssx[INKEUUARRs1] - 1)
		KEYXx -= (SETSTRssx[INKEUUARRs1] - 1);
	KEYXx %= COUNTEERXXx;
 
	while(KEYXx--){
 
		INKEUUARRs1 = ARRAYSX1[INKEUUARRs1 - 1];
	}
 
	cout << INKEUUARRs1;
 
}
int main(){
    int t;
    //cin>>t;
   t=1;
    while(t--){
       solvexXx();
    }
    return 0;
}

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
l=[]*n
for i in range(n):
    b=[0,0]
    b[0]+=i+1
    b[1]+=a[i]
    l.append(b)
c=0
ne=0
l1=[0]*n
while True:
    if c==k:
        print(l[ne][1])
        exit()
    ne+=-ne+l[ne][1]-1
    c+=1
    if l1[ne]==0:l1[ne]+=1
    else:
        roop_act+=ne
        break

roop_c=0
while True:
    if c+roop_c==k:
        print(l[ne][1])
        exit()
    if l1[ne]==1:l1[ne]+=1
    else:break
    ne+=-ne+l[ne][1]-1
    roop_c+=1

re=(k-c)%roop_c
if re==0:print(l[ne][0])
else:
    for i in range(re):
        if i==re-1:print(l[ne][1])
        ne+=-ne+l[ne][1]-1

Submission status: Runtime Error

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

Visit = [False for i in range(n+1)]

loop_st,loop_end,loop_len = 0,0,0
st = 1
releki = []
for i in range(10000000000000):
    
    if Visit[st] == True:
        loop_key = st
        loop_st = releki.index(loop_key)
        loop_end = len(releki)-loop_st
        loop_len = len(releki)-loop_st-1
        break
    releki.append(st)
    Visit[st] = True
    st = A[st-1]
k-= loop_st
print(releki[loop_len%k])

Submission status: Runtime Error

Solution code:
import sys

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

z = 1
p = [1]
for _ in range(k):
    z = a[z-1]
    if z in p:
        p.append(z)
        break
    p.append(z)

# 周期の来る前の回数
num = p.index(p[-1])

p = p[num:]

# 周期
pn = len(p)-1

k -= num

# 回数/周期のあまり
anum = k%pn
print(p[anum])

Submission status: Runtime Error

Solution code:
n , k = map(int, input().split())
dic = {}
data = input().split()
for i in range(n):
    dic.setdefault(i+1 , int(data[i]))

# find common
tmp = {}
next_t = dic[1]
for i in range(10000):
    if next_t not in tmp :
        tmp.setdefault(next_t,1)
    else:
        tmp[next_t]+=1
    next_t = dic[next_t]

common  = []
has_one = False
for k,v in tmp.items():
    if v!= 1:
        common.append(k)
    else:
        has_one = True

if has_one:
    print(common[k%3])
else:
    print(common[k%3])

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
X = [-1 for j in range(N)]
X[0] = 0
Y = [0]
i = 0
Num = 0
MM = 0
for k in range(1,N):
  i = A[i]-1
  if k = K:
    MM = 1
    P = i
  elif X[i] != -1:
    Num = X[i]
    break
  else:
    X[i] = k
    Y.append(i)
Y = Y[Num:]
B = (K-Num)%len(Y)
if MM = 1:
  print(P+1)
else:
  print(Y[B]+1)

Submission status: Runtime Error

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 position in exp:
      exp.append(position)
    else:
      break
  init = exp.index(position)
  res = (k - init) % (count - init)
  print(exp[init + res])

Submission status: Runtime Error

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

from collections import deque 
tmp = 1
num = deque()
 
for i in range(N):
    num.append(tmp)
    if tmp == A[tmp-1]:
        judge = tmp
        flag1 = 1
        break
    tmp = A[tmp-1]
    if tmp in num:
        judge = tmp
        flag2 = 1
        break

if flag2 == 1:
    num_index = num.index(judge)
    print(num[(K-num_index)%(len(num)-num_index) + num_index])
elif flag1 == 1:
    if K >= len(num):
        print(judge)
    else:
        print(num[K-1])

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
d=[0]
w=set([0])
x=0
for i in range(n):
    if a[x]-1 not in w:
        d.append(a[x]-1)
        w.add(a[x]-1)
        x=a[x]-1
    else:
        f=a[x]-1
        break

#print(d)
if k<len(d):
    print(d[k])
else:
    x=k-len(d)
    y=d.index(d[f])
    z=len(d)-y+1
    #print(d,y)
    #exit()
    print(d[y+x%z]+1)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
teleport = dict()
for i, a in enumerate(A):
    teleport[i+1] = a
# teleport

state = 1
connect = []
looplen= 0
for n in range(K):
    connect.append(state)
    state = teleport[state] 
    if state in connect:
        loop_init = connect.index(state)
        looplen = n-connect.index(state)+1
        break
index = (k-loop_init)%looplen
end = connect[index+loop_init]
print(end)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
do = a[0]-1
ex = [0 for i in range(n+1)]
cntnum = [0 for i in range(n+1)]
cntnum [0] = 0
cntnum [do] = 1
ex[0] = 1
ex[do] = 1
cnt = 1
flag = 0
for i in range(k):
    do = a[do]-1
    if ex[do] == 1:
        cnt+=1
        ros = cnt - cntnum[do]
        aos = cntnum[do]-1
        if cntnum[do] == 0:
            aos = 0
            flag = 1
        break
    cnt += 1
    ex[do] = 1
    cntnum[do] = cnt



if k == ros:
    print(do+1)
    exit()


temp = (k - aos)%ros

if flag != 1:
    temp -= 1

ans = do

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

print(ans+1)

Submission status: Runtime Error

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

if K <= 200000:
  i = 1
  for _ in range(K):
    i = A[i-1]
  print(i)
  exit()

visited = {1}
order = []

i = 1
for count in range(1, 200001):
  i = A[i-1]
  if i in visited:
    break
  else:
    visited.add(i)
  order.append(i)

idx = order.index(i)
order2 = order[idx:]
mod = (K-idx) % len(order2)

print(order2[mod-1])

Submission status: Runtime Error

Solution code:
n,k=map(int, input().split())
a=list(map(int, input().split()))
x=1
loop=0
loopx=0
check=[0]*n
check[0]=1
owari=0
for i in range(1,k+1):
    x=a[x-1]
    check[x-1]+=1
    #print(x,'000')
    if check.count(2)==1:
        loopx=i
        #print(i,'a')
    if max(check)==3:
        check[x-1]=2
        loop=i
        #print(i,'b')
        break

    if i==k+1:
        loop=i
        owari=1

if owari==1:
    print(x)
    exit()

s=loop-loopx
yobun=loopx-s
amari=(k-yobun)%s
x=1
for i in range(yobun+amari):
    x = a[x - 1]

print(x)

Submission status: Runtime Error

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

rireki = [0] * (n+1)
curr_c = 1
rireki[1] = 0

no_loop_count = k
loop_cnt = 0

for i in range(k):
    next_c = a_list[curr_c-1]
    # print(i, curr_c, next_c)
    if next_c == 1:
        no_loop_count = 0
        loop_cnt = i + 1
        break
    elif rireki[next_c] == 0:
        rireki[next_c] = i+1
    else:
        # print(next_c)
        no_loop_count = rireki[next_c] -1
        loop_cnt = i - no_loop_count
        break
    curr_c = next_c


if k <= no_loop_count:
    ans = rireki.index(k)
else:
    # print('k',k)
    # print('no', no_loop_count)
    # print('lo', loop_cnt)
    ind = (k-1-no_loop_count)%loop_cnt +1
    rireki_fix = [i-no_loop_count for i in rireki]
    # print(ind, 'ind')
    ans = rireki_fix.index(ind)
    # print(rireki_fix)

print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
loop_=[1]
l_set=set()
lst=list(map(int,input().split()))

tar=None
for i in range(k):
    num=lst[loop_[-1]-1]
    if num in l_set:
        tar=num
        break
    else:
        loop_.append(num)
        l_set.add(num)

if tar==None:
    print(loop_[k])
    exit()    
loop__=loop_[loop_.index(tar):]
 
if k<=len(loop_):
    print(loop_[k])
else:
    num=k+1-len(loop_)
    print(loop__[num%len(loop__)-1])

Submission status: Runtime Error

Solution code:
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
MOD = 10**9 + 7

n, k = MAP()
a = LIST()
tugi = [0]+a
cyclestart = []
town  =1
temp = [town, ]

while True:
    town = tugi[town]
    if town in temp:
        i = temp.index(town)
        notcycle = temp[:i]
        cycle = temp[i:]
        cyclestart.append(town)
        break
    temp.append(town)
k -= len(notcycle)
print(cycle[k%len(cycle)])

Submission status: Runtime Error

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

t = 1
tpass = [1]
k = 0
for i in range(K):
    temp = A[t-1] 
    if temp in tpass:
        idx = tpass.index(temp)
        l = len(tpass)
        break
    else:
        t = temp
        tpass.append(temp)
        k += 1

a = K - k
loop = l - idx
b = a % loop 


temp2 = tpass[idx:]

ans = temp2[b-1]

print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
routs = {}
tereporter = list(map(int, input().split()))
for i in range(N):
  routs[i] = tereporter[i]
present_location = 1
for i in tange(K):
  present_location = routs[present_location]
print(present_location)

Submission status: Runtime Error

Solution code:



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

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

array1=[1]
#ary2=[]
f=1
#b=li[li[1]]
i=0
j=0
b_n=0
for n in range(b):
    i=li[i]-1
    #print(i)

    if i in array1:
        b_n=1
        #print(i)
        array1.append(i)
        if i==array1[i+1]:
            print(i+1)

            break
        else:

            ary2=array1[array1.index(i):-1]
            #print(ary2)
            #print(b-j)
            c=(b-j)%len(ary2)
            print(ary2[c-1]+1)
            j=n
            #print(n)
            break

    else:
        array1.append(i)


if b_n==0:
    print(i)

Submission status: Runtime Error

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

# print(a)
cnt = [0]*(10**5)
cnt2 = [0]*(10**5)#何回目に出てきたか
t = []
nxt = 0
loop = 0

for i in range(10**5):
    cnt[nxt] += 1
    if cnt[nxt] >= 2:
        # print("i: " + str(i))
        # print("nxt: " + str(nxt))
        loop = i - cnt2[nxt]
        modC = max(0, cnt2[nxt])
        break
    cnt2[nxt] = i
    t.append(nxt)
    nxt = a[nxt]

modK = (k-modC)%loop
# print("-------")
# print(t)
# print("modC: " + str(modC))
# print("modK: " + str(modK))
# print("loop: " + str(loop))
# print(modK)
# print(loop)
# print("-------")

print(t[modC + modK] + 1)

Submission status: Runtime Error

Solution code:
import collections


def main():
    N, K = list(map(int, input().split(' ')))
    An  = list(map(int, input().split(' ')))
    
    dic = {}
    li = []
    mae = []
    ato = []
    for i in range(len(An)):
        dic[str(i+1)] = An[i]
        li.append([i+1, An[i]])
        # mae.append(i+1)
        # ato.append(An[i])

    status = 1
    ittatokoro = [1]
    for k in range(K):
        pre_s = status
        status = dic[str(status)]
        if status not in ittatokoro:
            ittatokoro.append(status)
        else:
            ittatokoro.append(status)
            break
    # print('最後の位置:', status) # 
    # print(ittatokoro, k)
    
    # c = collections.Counter(ittatokoro).most_common()[0] # nがk回数
    # K += 1 #  saisyo 1 ni irus
    START = 0
    for i, iku in enumerate(ittatokoro):
        if iku == status:
            START = i
            break
    # print('START:', START)
    
    S_ittatoko = ittatokoro[:START]
    junkan = ittatokoro[START:-1]
    len_junkan = len(junkan)
    # print('junkan:', junkan, len_junkan, S_ittatoko)
    
    junkannmadeno_hosuu = K - START
    num_junkan_kaisuu = junkannmadeno_hosuu // len_junkan
    amari_junkan_kaisuu = junkannmadeno_hosuu % len_junkan
    # print('循環回数:', num_junkan_kaisuu, amari_junkan_kaisuu)

    total = num_junkan_kaisuu * len_junkan + amari_junkan_kaisuu
    
    nokori = junkannmadeno_hosuu - total
    print(junkan[amari_junkan_kaisuu])
    
    
    
main()

Submission status: Runtime Error

Solution code:
import sys

N,K = map(int, sys.stdin.readline().strip().split())
A = list(map(int, sys.stdin.readline().strip().split()))

pos = 1

if K <= len(A):
    while K > 0:
        pos = A[pos-1]
        K -= 1
    print(pos)
    sys.exit()

hist = [1]

while True:
    pos = A[pos-1] # next
    if count > 0 and pos in hist:
        prefix = hist.index(pos)
        cycle = hist[hist.index(pos):]
        break
    hist.append(pos)

# print(count)
# print(hist)
ans = (K - prefix) % len(cycle)
print(cycle[ans])

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 21:41:44 2020

@author: Kei
"""

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

A = [0]*N
town = [0]*N

A = input().split()

A = [int(s) for s in A]

temp = 0

for i in range(0,K+1):
    town[temp-1] += 1 
    
    if town[temp-1] == 2:
        roop = i
        break
    
    temp = A[temp-1]

roop_len = roop

i = 0
while temp != A[i]:
#    print(str(temp)+"=="+str(A[i]))
    roop_len -=1
    i += 1

ans = (K+1-i)%roop_len

goal = 0
for i in range(0,i+roop_len-ans):
    goal = A[goal-1]

print(goal)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
memo = [-1] * N
checked_num = {}

teleporter = A[0]
memo[0] = teleporter
repeat_point = -1
flag = False

for i in range(1, N):
    memo[i] = A[teleporter-1]
    teleporter = A[teleporter-1]
    checked_num[memo[i]] = None
    if memo[i] in checked_num and flag == False:
        repeat_point = i
        flag = True

start_point = memo.index(memo[repeat_point])
repeat = repeat_point - start_point
# print(memo, start_point, repeat_point)

if K <= N:
    print(memo[K-1])
else:
    mod = K % repeat
    print(memo[mod-1])

Submission status: Runtime Error

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

lst = []
visit_now = 1
while not visit_now in lst:
    lst.append(visit_now)
    visit_now = a[visit_now - 1]

start = lst.index(visit_now)
loop_num = n - start - 1
loop_list = lst[start:]

k -= start
k %= loop_num

print(loop_list[k])

Submission status: Runtime Error

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

import numpy as np



Nstock = np.zeros(N)

cpos = 1
Nstock[cpos - 1] = 1
stock = [cpos]
loop = []

idx = 0
for i in range(K):
    cpos = A[cpos-1]
    if Nstock[cpos - 1]  == 1:
        idx = stock.index(cpos)
        loop = stock[idx:]
        break
    Nstock[cpos - 1] = 1
    stock.append(cpos)
    
v = (K - idx) 
a = v %len(loop)

print(loop[a])

Submission status: Runtime Error

Solution code:
n,k=list(map(int,input().split()))
A=list(map(int,input().split()))
start,i=1,0
root=[1]

for j in range(k):
  start=A[start-1]
  if start in root:
    i = start
    break
  root.append(start)
  
if k <= len(root):
  print(root[k-1])
else:
  newroot=root[i-1:]
  ans=(k-len(root))%len(newroot)
  print(newroot[ans])