Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

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

ans = 1
j = 0
for a in A:
  ans = ans*a
  if(a == 0):
    j -= 100 
    break
  if(ans > 10**18):
    j = 1
    
if(j <= 0):
  print(ans)
else:
  print(-1)


### FIXED CODE ###

N = int(input())
A = list(map(int,input().split()))
         
if(0 in A):
  ans = 0 
else:
  ans = 1       
  for a in A:
    ans *= a
    if(ans > 10**18):
      ans = -1
      break
    if(len(str(ans))>=2):
     if(str(ans)[1] == 'e'):
      ans = -1
      break
         
print(ans)
### BUGGY CODE ###


# 素因数分解（辞書型で返ってくるので今回は使いにくい）
"""
pf={}
n = int(input())
for i in range(2,int(n**0.5)+1):
    while n % i == 0:
        pf[i] = pf.get(i,0)+1
        n//= i
if n > 1 : pf[n] = 1
print(pf)
"""
"""
# Return a list of the prime factors for a natural number bigger than 1
def trial_division(n):
    if n < 2:
        return []

    prime_factors = []

    for i in range(2, int(n**0.5)+1):
        # nがi（の累乗）で割り切れるかを調べる
        while n % i == 0:
            # nがiで割り切れる場合、iを素因数としてリストに追加する
            prime_factors.append(i)
            # nをiで割った商で更新しておく
            n //= i
    # nの平方根より大きい素因数が存在する場合
    if n > 1:
        prime_factors.append(n)

    return prime_factors

n = int(input())
# print(trial_division(n)) # 結果がリストで返ってくる
"""

n=int(input())

for i in range(1,100000):
    for j in range(1,i+1):
        seki=i*j
        if seki==n:
            print(i+j-2)
            exit()


### FIXED CODE ###


# 素因数分解（辞書型で返ってくるので今回は使いにくい）
"""
pf={}
n = int(input())
for i in range(2,int(n**0.5)+1):
    while n % i == 0:
        pf[i] = pf.get(i,0)+1
        n//= i
if n > 1 : pf[n] = 1
print(pf)
"""
"""
# Return a list of the prime factors for a natural number bigger than 1
def trial_division(n):
    if n < 2:
        return []

    prime_factors = []

    for i in range(2, int(n**0.5)+1):
        # nがi（の累乗）で割り切れるかを調べる
        while n % i == 0:
            # nがiで割り切れる場合、iを素因数としてリストに追加する
            prime_factors.append(i)
            # nをiで割った商で更新しておく
            n //= i
    # nの平方根より大きい素因数が存在する場合
    if n > 1:
        prime_factors.append(n)

    return prime_factors

n = int(input())
# print(trial_division(n)) # 結果がリストで返ってくる
"""

""" TLE
n=int(input())

for i in range(1,10000):
    for j in range(1,i+1):
        seki=i*j
        if seki==n:
            print(i+j-2)
            exit()
"""

# 対称性よりNの√を取り、1~√nまで全探索
import sys
input = sys.stdin.readline
 
N=int(input())
ans=10**12
for i in range(1,int(N**0.5)+1):
    if N%i==0: # 割り切れる場合
        ans=min(ans,i+N//i) # N//iはもう一個の解 N=i*N//i
print(ans-2) # -2はもともと(1,1)にいるからその分の差し引き
### BUGGY CODE ###

n=int(input())
a=[]
for i in range(n):
	a.append(list(map(int,input().split())))
d=[[]for _ in range(n**2)]
start=[0]*(n**2)
for i in range(n):
	for j in range(n-2):
		p=[i,a[i][j]-1];q=[i,a[i][j+1]-1]
		if i>a[i][j]-1:
			p=[a[i][j]-1,i]
		if i>a[i][j+1]-1:
			q=[a[i][j+1]-1,i]
		start[p[0]*n+p[1]]+=1
		start[q[0]*n+q[1]]=-10**7
		d[p[0]*n+p[1]].append(q[0]*n+q[1])
st=-1
for i in range(n**2):
	if start[i]>0:
		st=i
		break
if st==-1:
	print(-1)
	exit()
from collections import deque
stack=deque([st])
deep=[1]*(n**2)
while stack:
	p=stack.pop()
	for x in d[p]:
		stack.append(x)
		deep[x]=deep[p]+1
print(max(deep))

### FIXED CODE ###

def main():
	from collections import deque
	n=int(input())
	battle=n*(n-1)//2
	lis=[[] for i in range(battle)]
	num=[-1]*(n**2)
	cnt=-1
	for x in range(n**2):
		if x//n<x%n:
			cnt+=1
			num[x]=cnt
	for i in range(n):
		a=list(map(int,input().split()))
		for j in range(n-2):
			x=a[j]-1
			y=a[j+1]-1
			px=num[min(i*n+x,x*n+i)]
			py=num[min(i*n+y,y*n+i)]
			lis[px].append(py)
	node_in=[0]*(battle)
	for i in range(battle):
		for x in lis[i]:
			node_in[x]+=1
	zero=deque([])
	days=[10**9]*(battle)
	for i in range(battle):
		if node_in[i]==0:
			zero.append(i)
			days[i]=1
	while zero:
		r=zero.popleft()
		for x in lis[r]:
			node_in[x]-=1
			if node_in[x]==0:
				zero.append(x)
				days[x]=days[r]+1
	if 10**9 in days:
		print(-1)
	else:
		print(max(days))
if __name__ == '__main__':
	main()
### BUGGY CODE ###

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

for n in range(N):
  print(A.count(n+1))

### FIXED CODE ###

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

ans = [0]*n
for a in A:
  ans[a-1]+=1
for a in ans:
  print(a)
### BUGGY CODE ###

#!/usr/bin/env python3
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 7)

N = int(readline())
S = readline()
count = 0
for i in range(0,1000):
    c = (i//100,(i//10)%10,i%10)
    f = 0
    for j in range(0,N):
        if int(S[j]) == int(c[f]):
            f += 1
        if f == 3:
            break
    if f == 3:
        count += 1
            
print(count)

### FIXED CODE ###

#!/usr/bin/env python3
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 7)

N = int(readline())
S = readline()
count = 0
for i in range(10):
    a = S.find(str(i))
    if a == -1: 
        continue
    for j in range(10):
        b = S.find(str(j),a+1)
        if b == -1: 
            continue
        for k in range(10):
            c = S.find(str(k),b+1)
            if c != -1: count +=1
print(count)
### BUGGY CODE ###

#ABC125_C
import fractions
from functools import reduce

def gcd(nums):
    return reduce(fractions.gcd,nums)

N=int(input())
A=list(map(int,input().split()))
ans=1
       
for i in range(N):
       temp=A.copy()
       temp.pop(i)
       if gcd(temp) > ans:
           ans=gcd(temp)
print(ans)   

### FIXED CODE ###

#ABC125_C

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

def gcd(x,y):
    if x<y:
        x,y=y,x
    if y==0:
        return x
    return gcd(x%y,y)

LCD=[A[0]]
RCD=[A[-1]]
for i in range(1,N):
    LCD.append(gcd(LCD[-1],A[i]))
    RCD.append(gcd(RCD[-1],A[-i-1]))

ans=1

if RCD[N-2]>ans:
    ans=RCD[N-2]

for i in range(1,N-1):
    if gcd(LCD[i-1],RCD[N-i-2])>ans:
        ans=gcd(LCD[i-1],RCD[N-i-2])

if LCD[N-2]>ans:
    ans=LCD[N-2]
print(ans)
### BUGGY CODE ###

n = int(input())
s = input()
a = s.count("R")
b = s.count("G")
c = s.count("B")
x = 0
for i in range(n-2):
  for j in range(i+1, n-1):
    if 2*j-i<= n-1 and len({s[i], s[j], s[2*j-i]})==3:
        x += 1
print(a*b*c-x)


### FIXED CODE ###

n = int(input())
s = input()
a = s.count("R")
b = s.count("G")
c = s.count("B")
z = a*b*c
R=[]
G=[]
B=[]
for i in range(n):
  if s[i]=="R":
    R.append(i)
  elif s[i]=="G":
    G.append(i)
  else:
    B.append(i)
x = 0
for i in R:
  for j in G:
    if 0 <= 2*j-i <= n-1 and s[2*j-i]=="B":
      x+=1
    if 0 <= 2*i-j <= n-1 and s[2*i-j]=="B":
      x+=1
    if (i+j)%2==0 and s[(i+j)//2]=="B":
      x+=1
print(z-x)
### BUGGY CODE ###

n=int(input())
s=input()
c=[[0,0,0] for _ in range(n+1)]
R=G=B=0
for j,i in enumerate(s):
    if i=="R":
        R+=1
    elif i=="G":
        G+=1
    else:B+=1
    c[j+1]=[R,G,B]
a=0
for i in range(1,n-1):
    for j in range(i):
        k=3-"RGB".index(s[i])-"RGB".index(s[j])
        if s[i]!=s[j]:
            a+=c[-1][k]-c[i][k]
            if 2*i-j<=n-1:
                if s[2*i-j]!=s[i] and s[2*i-j]!=s[j]:
                    a-=1
print(a)

### FIXED CODE ###

n=int(input())
s=input()
c=s.count
a=c("R")*c("G")*c("B")
for i in range(n-2):
    for j in range((n-i+1)//2):
        if s[i]!=s[i+j] and s[i+j]!=s[i+2*j] and s[i+2*j]!=s[i]:
            a-=1
print(a)
### BUGGY CODE ###

import numpy as np
 
N, M = map(int, input().split())
As = list(map(int, input().split()))
As = np.array(As)
 
out = 0
Bs = []
Cs = []
for _ in range(M):
  b, c = map(int, input().split())
  Bs.append(b)
  Cs.append(c)
both = list(zip(Cs, Bs))
both.sort()
Cs, Bs = zip(*both)
for k in reversed(range(M)):
  As.sort()
  b = Bs[k]
  c = Cs[k]
  cnt = (As < c).sum()
  if cnt == 0:
    break
  else:
    if b > cnt:
      out += cnt * c
      As = As[cnt:]
    else:
      out += b * c
      As = As[b:]
print(out + As.sum())

### FIXED CODE ###

N, M = map(int, input().split())
As = list(map(int, input().split()))
ones = [1 for _ in range(N)]
Bs = []
Cs = []
both = list(zip(As, ones))
for _ in range(M):
  b, c = map(int, input().split())
  both.append((c, b))
both.sort()
a, b = zip(*both)
cnt = 0
out = 0
for k in reversed(range(N+M)):
  if N - cnt > b[k]:
    out += a[k] * b[k]
    cnt += b[k]
  else:
    out += a[k] * (N - cnt)
    break
print(out)
### BUGGY CODE ###

from sys import stdin
N = int(stdin.readline().rstrip())
print(0)
s = input()
cnt = 0
N = (N-1)//2
if s == "Male":
    while True:
        cnt += 1
        print(N)
        s = input()
        if s == "Male" and N % 2 == 0:
            N += max(1,(L-N)//2)
        elif s == "Female" and N % 2 != 0:
            N += max(1,(L-N)//2)
        elif s == "Vacant":
            break
        else:
            N -= max((N//2),1)
        if cnt > 25:
            break
        
elif s == "Female":
    while True:
        cnt += 1
        print(N)
        s = input()
        if s == "Female" and N % 2 == 0:
            N += max(1,(L-N)//2)
        elif s == "Male" and N % 2 != 0:
            N += max(1,(L-N)//2)
        elif s == "Vacant":
            break
        else:
            N -= max((N//2),1)
        if cnt > 25:
            break

### FIXED CODE ###

from sys import stdin
N = int(stdin.readline().rstrip())
r = N-1
l = 0
print(0)
s = input()
cnt = 0
mid = (r+l)//2
if s == "Male":
    for _ in range(25):
        print(mid)
        s = input()
        if s == "Male" and mid % 2 == 0:
            l += max((r-l)//2,1)
        elif s == "Female" and mid % 2 != 0:
            l += max((r-l)//2,1)
        elif s == "Vacant":
            break
        else:
            r -= max((r-l)//2,1)
        mid = (r+l)//2
        
elif s == "Female":
    for _ in range(25):
        print(mid)
        s = input()
        if s == "Female" and mid % 2 == 0:
            l += max((r-l)//2,1)
        elif s == "Male" and mid % 2 != 0:
            l += max((r-l)//2,1)
        elif s == "Vacant":
            break
        else:
            r -= max((r-l)//2,1)
        mid = (r+l)//2
### BUGGY CODE ###

H, W, M = map(int, input().split())
cnth = [[0, i] for i in range(H)]
cntw = [[0, i] for i in range(W)]
L = [[False for _ in range(W)] for _ in range(H)]
for _ in range(M):
    h, w = map(lambda x: int(x) - 1, input().split())
    cnth[h][0] += 1
    cntw[w][0] += 1
    L[h][w] = True
cnth.sort(reverse=True)
cntw.sort(reverse=True)
mh = set()
ph = cnth[0]
for h in cnth:
    if ph[0] == h[0]:
        mh.add(h[1])
    else:
        break
    ph = h
mw = set()
pw = cntw[0]
for w in cntw:
    if pw[0] == w[0]:
        mw.add(w[1])
    else:
        break
    pw = w
max = cnth[0][0] + cntw[0][0]
for h in mh:
    for w in mw:
        if not (L[h][w]):
            print(max)
            break
    else:
        continue
    break
else:
    print(max - 1)


### FIXED CODE ###

def main():
    H, W, M = map(int, input().split())
    cnth = [[0, i] for i in range(H)]
    cntw = [[0, i] for i in range(W)]
    L = set()
    for _ in range(M):
        h, w = map(lambda x: int(x) - 1, input().split())
        cnth[h][0] += 1
        cntw[w][0] += 1
        L.add((h, w))
    cnth.sort(reverse=True)
    cntw.sort(reverse=True)
    mh = set()
    ph = cnth[0]
    for h in cnth:
        if ph[0] == h[0]:
            mh.add(h[1])
        else:
            break
        ph = h
    mw = set()
    pw = cntw[0]
    for w in cntw:
        if pw[0] == w[0]:
            mw.add(w[1])
        else:
            break
        pw = w
    maxans = cnth[0][0] + cntw[0][0]
    for h in mh:
        for w in mw:
            if not ((h, w) in L):
                print(maxans)
                break
        else:
            continue
        break
    else:
        print(maxans - 1)
if __name__ == "__main__":
    main()
### BUGGY CODE ###

n = int(input())
D ={}
for i in range(n):
    s = input()
    if s in D.keys(): #sが辞書Dにあるのかチェック(これはある場合)
        D[s] += 1 #D[s] += 1 ->{'s':今までに出てきた回数+1}となる
    else:  #sが辞書Dにない場合
        D[s] = 1 #D[s] = 1 ->{'s':1}となる
poll = [k for k,v in D.items() if v == max(D.values())]
print('\n'.join(sorted(poll)))

### FIXED CODE ###

n = int(input())
D ={}
for i in range(n):
    s = input()
    if s in D.keys(): #sが辞書Dにあるのかチェック(これはある場合)
        D[s] += 1 #D[s] += 1 ->{'s':今までに出てきた回数+1}となる
    else:  #sが辞書Dにない場合
        D[s] = 1 #D[s] = 1 ->{'s':1}となる
maxD = max(D.values())
poll = [k for k,v in D.items() if v == maxD]
print('\n'.join(sorted(poll)))
### BUGGY CODE ###

n, k = map(int, input().split())
k = min(n - 1, k)
h = list(map(int, input().split()))
cost = [0 for _ in range(k)]
for i, hi in enumerate(h):
    if i == 0: continue
    (cs, hs) = (k - i, 0) if k > i else (0, i - k)
    new_cost = min([ck + abs(hi - hk) for ck, hk in zip(cost[cs:], h[hs:])])
    cost = cost[1:] + [new_cost]
print(cost[k - 1])


### FIXED CODE ###

n, k = map(int, input().split())
k = min(n - 1, k)
h = list(map(int, input().split()))
cost = [0 for _ in range(n)]
for i, hi in enumerate(h):
    if i == 0: continue
    st = i - k if i > k else 0
    cost[i] = min([ck + abs(hi - hk) for ck, hk in zip(cost[st:i], h[st:i])])
print(cost[-1])
### BUGGY CODE ###

#!/usr/bin/env python
# coding: utf-8

# In[3]:


import numpy as np


# In[25]:


N = int(input())
data = []
for i in range(N):
    data.append((list(map(int, input().split()))))


# In[26]:


data = np.array(data)


# In[27]:


sorted_data = data[np.argsort(data[:, 1])]


# In[28]:


flag = 0
for i in range(N):
    if sum(sorted_data[:i+1, 0]) > sorted_data[i, 1]:
        flag = 1
        break

if flag == 0:
    print("Yes")
else:
    print("No")


# In[ ]:






### FIXED CODE ###

#!/usr/bin/env python
# coding: utf-8

# In[3]:


import numpy as np


# In[42]:


N = int(input())
data = []
for i in range(N):
    data.append((list(map(int, input().split()))))


# In[43]:


data = np.array(data)


# In[44]:


sorted_data = data[np.argsort(data[:, 1])]
cumsum_data = np.cumsum(sorted_data[:,0])


# In[45]:


flag = 0
for i in range(N):
    if cumsum_data[i] > sorted_data[i, 1]:
        flag = 1
        break

if flag == 0:
    print("Yes")
else:
    print("No")


# In[ ]:
### BUGGY CODE ###

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors

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

lis = {}
flg1 = True

for i in range(n):
  temp =  make_divisors(a[i])
  for j in temp:
    if j == 1:
      continue
    if not  j in lis:
      lis[j]=1
    else:
      flg1 = False
      lis[j]+=1
      if lis[j]==n:
        print("not coprime")
        quit()
      
if flg1:
  print("pairwise coprime")
else:
  print("setwise coprime")

### FIXED CODE ###

from math import gcd
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return set(a)
  
n = int(input())
a = list(map(int, input().split()))
dic = {}
g = a[0]
flg = True
for i in range(n):
  g = gcd(g, a[i])
  if flg:
    tmp = prime_factorize(a[i])
    for j in tmp:
      if j in dic:
        flg = False
      else:
        dic[j]=1
        
if flg:
  print("pairwise coprime")
elif g == 1:
  print("setwise coprime")
else:
  print("not coprime")
### BUGGY CODE ###

r1,c1,r2,c2 = map(int, input().split())

def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def comb(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

def g(x,y):
    return comb(x+y+2,y+1)-1

ans=g(r2,c2) - g(r1-1,c2) - g(r2,c1-1) + g(r1-1,c1-1)

mod=10**9+7
print(ans%mod)

### FIXED CODE ###

r1,c1,r2,c2 = map(int, input().split())
def find_power(n,mod=10**9+7):
    powlist=[0]*(n+1)
    powlist[0]=1
    powlist[1]=1
    for i in range(2,n+1):
        powlist[i]=powlist[i-1]*i%(mod)
    return powlist

def find_inv_power(n,mod=10**9+7):
    powlist=find_power(n)
    check=powlist[-1]
    first=1
    uselist=[0]*(n+1)
    secondlist=[0]*30
    secondlist[0]=check
    secondlist[1]=check**2
    for i in range(28):
        secondlist[i+2]=(secondlist[i+1]**2)%(10**9+7)
    a=format(10**9+5,"b")
    for j in range(30):
        if a[29-j]=="1":
            first=(first*secondlist[j])%(10**9+7)
    uselist[n]=first
    for i in range(n,0,-1):
        uselist[i-1]=(uselist[i]*i)%(10**9+7)
    return uselist

mod = 10**9+7
NUM = (2*10**6)+100
p_lis=find_power(NUM,mod)
ip_lis=find_inv_power(NUM,mod)

def comb(n,r,mod=10**9+7):
    if n<r:
        return 0
    elif n>=r:
        return (p_lis[n]*ip_lis[r]*ip_lis[n-r])%(mod)
def g(x,y):
    return comb(x+y+2,y+1)-1

ans=g(r2,c2) - g(r1-1,c2) - g(r2,c1-1) + g(r1-1,c1-1)
print(ans%mod)
### BUGGY CODE ###

a,b,x=map(int,input().split())
ans=0
for i in range(a,b+1):
  if i%x==0:
    ans+=1
print(ans)

### FIXED CODE ###

a,b,x=map(int,input().split())
print(b//x-(a-1)//x)
### BUGGY CODE ###

def ex(x):
    s = 0
    p = 1/x
    for i in range(1, x+1):
        s = s + p*i
    return s


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

m = 0

for j in range(n-k+1):
    sum = 0
    for i in range(j, j+k):
        sum = sum + ex(p[i])
    m = max(sum, m)

print(m)

### FIXED CODE ###

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

temp= sum(p[:k])
ans = temp

for i in range(n-k):
    temp = temp - p[i]
    temp = temp + p[i+k]
    ans = max(temp, ans)
    
ans = (ans+k) / 2

print(ans)
### BUGGY CODE ###

h, w, k = map(int, input().split())
s = [list(map(int, list(input()))) for _ in range(h)]
result = []
if h*w<=k:
    result.append(0)
else:
    for i in range(2**(h-1)):
        checker, num = 0, i
        while num > 0:
            checker += num%2
            num >>= 1
        x = 0
        c = [0 for _ in range(checker+1)]

        for j in range(w):
            num = i
            p = 0
            nex = [0 for _ in range(checker+1)]
            for m in range(h):
                nex[p] += s[m][j]
                p += num%2
                num = num >> 1
            if max(nex) > k:
                x = -1
                break            
            
            if all(nex[m]+c[m] <= k for m in range(checker+1)):
                c = [c[I]+nex[I] for I in range(checker+1)]
            else:
                x += 1
                c = nex
        if x >= 0:
            result.append(checker+x)
print(min(result))

### FIXED CODE ###

h, w, k = map(int, input().split())
s = [list(map(int, list(input()))) for _ in range(h)]
result = []
if h*w<=k:
    result.append(0)
else:
    for i in range(2**(h-1)):
        checker, num = 0, i
        while num > 0:
            checker += num%2
            num >>= 1
        x = 0
        c = [0 for _ in range(checker+1)]
        
        num = i
        p = 0
        nex = [0 for _ in range(checker+1)]
        for m in range(h):
            nex[p] += s[m][0]
            p += num%2
            num = num >> 1
        if max(nex) > k:
            x = float('inf')
            continue

        if all(nex[m]+c[m] <= k for m in range(checker+1)):
            c = [c[I]+nex[I] for I in range(checker+1)]
        else:
            x += 1

        for j in range(1, w):
            num = i
            p = 0
            nex = [0 for _ in range(checker+1)]
            for m in range(h):
                nex[p] += s[m][j]
                p += num%2
                num = num >> 1
            if max(nex) > k:
                x = float('inf')
                break            
            
            if all(nex[m]+c[m] <= k for m in range(checker+1)):
                c = [c[I]+nex[I] for I in range(checker+1)]
            else:
                x += 1
                c = nex
        result.append(checker+x)
print(min(result))
### BUGGY CODE ###

import numpy as np
n=int(input())
a=list(map(int,input().split()))
ans=1
for i in range(n):
    ans=ans*a[i]
    if ans>10**18 and not 0 in a:
      print(-1)
      exit()
if ans>10**18:
    anscheck=False
else:
    anscheck=True
print(ans if anscheck else -1)

### FIXED CODE ###

import numpy as np
n=int(input())
a=list(map(int,input().split()))
ans=1
if 0 in a:
    print(0)
    exit()
for i in range(n):
    ans=ans*a[i]
    if ans>10**18 and not 0 in a:
      print(-1)
      exit()
if ans>10**18:
    anscheck=False
else:
    anscheck=True
print(ans if anscheck else -1)
### BUGGY CODE ###

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

counter = 0
place_list = []
next = 1
while True:
    
    if  next in place_list:
        break
        
    else:
        place_list.append(next)
        next = A[next-1]
        
    counter += 1

duration_cycle = len(place_list)- place_list.index(next)
if K <len(place_list):
    print(place_list[K])
else:
    print(place_list[(K-place_list.index(next))%duration_cycle+place_list.index(next)])


### FIXED CODE ###

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

counter = 0
place_list = []
place_set = set()
next = 1
while True:
    
    if  next in place_set:
        break
        
    else:
        place_list.append(next)
        place_set.add(next)
        next = A[next-1]
        
    counter += 1

duration_cycle = len(place_list)- place_list.index(next)
if K <len(place_list):
    print(place_list[K])
else:
    print(place_list[(K-place_list.index(next))%duration_cycle+place_list.index(next)])
### BUGGY CODE ###

import collections
import itertools
def main():
    N = int(input())
    A = list(map(lambda x:x-1 ,map(int, input().split())))

    coll = collections.Counter(A[1:])
    counter = [0]*N
    comb = [0]*N
    sum1 = 0
    for i in range(N):
        c=coll.get(i,0)
        counter[i] = c
        if c>1:
            comb[i] = len(list(itertools.combinations([i for i in range(c)],2)))
            sum1 += comb[i]
    print(sum1)

    for i in range(1,N):
        # ボールA[i-1]を復活させて、ボールA[i]を除外
        n = counter[A[i-1]]
        if n>=1:
            sum1 += n
        counter[A[i-1]] += 1
        n = counter[A[i]]
        if n>=2:
            sum1 -= n-1
        counter[A[i]] -= 1
        print(sum1)

main()


### FIXED CODE ###

from operator import mul
from functools import reduce
import collections

def combinations_count(n, r):
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

def main():
    N = int(input())
    A = list(map(lambda x:x-1 ,map(int, input().split())))

    coll = collections.Counter(A[1:])
    counter = [0]*N
    comb = [0]*N
    sum1 = 0
    for i in range(N):
        c=coll.get(i,0)
        counter[i] = c
        if c>1:
            comb[i] = combinations_count(c,2)
            sum1 += comb[i]
    print(sum1)

    for i in range(1,N):
        # ボールA[i-1]を復活させて、ボールA[i]を除外
        n = counter[A[i-1]]
        if n>=1:
            sum1 += n
        counter[A[i-1]] += 1
        n = counter[A[i]]
        if n>=2:
            sum1 -= n-1
        counter[A[i]] -= 1
        print(sum1)

main()