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

import math
import copy
from copy import deepcopy
import sys
import fractions
# import numpy as np
from functools import reduce
# import statistics
import decimal
import heapq
import collections
import itertools

sys.setrecursionlimit(100001)


# input = sys.stdin.readline
# sys.setrecursionlimit(10**6)

# ===FUNCTION===

def getInputInt():
    inputNum = int(input())
    return inputNum


def getInputListInt():
    outputData = []
    inputData = input().split()
    outputData = [int(n) for n in inputData]

    return outputData


def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList


def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList


# ===CODE===

n = int(input())
d = getInputListInt()


def combinations_count(n, r):
    if n <= 1:
        return 0
    else:
        return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

dic = {}
dic_ans = {}
dic_comb = {}

for key in d:
    if key in dic:
        dic[key] += 1
    else:
        dic[key] = 1

for i in range(n):
    ans = 0
    tmp_key = d[i]

    if tmp_key in dic_ans:
        print(dic_ans[tmp_key])
    else:
        for k in dic:
            if k == tmp_key:
                tmp_dic_idx = dic[k]-1
                if tmp_dic_idx in dic_comb:
                    ans += dic_comb[tmp_dic_idx]
                else:
                    tmp_calc = combinations_count(tmp_dic_idx, 2)
                    ans += tmp_calc
                    dic_comb[tmp_dic_idx] = tmp_calc
            else:
                tmp_dic_idx = dic[k]
                if tmp_dic_idx in dic_comb:
                    ans += dic_comb[tmp_dic_idx]
                else:
                    tmp_calc = combinations_count(tmp_dic_idx, 2)
                    ans += tmp_calc
                    dic_comb[tmp_dic_idx] = tmp_calc
        print(ans)
        dic_ans[tmp_key] = ans




### FIXED CODE ###

import sys
import re
import math
import collections
import decimal
import bisect
import itertools

# import copy
# import heapq
# from collections import deque
# import decimal

# sys.setrecursionlimit(100001)
INF = sys.maxsize
# MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===


def main():
    n = ni()
    d = na()
    c = collections.Counter(d)

    total = 0
    for v in c.values():
        total += v * (v - 1) // 2

    for i in range(n):
        v = c[d[i]]

        print(int(total - v + 1))


if __name__ == '__main__':
    main()
### BUGGY CODE ###

N, M, K = [int(item) for item in input().split()]
MOD = 10**9 + 7

n = 5 * 10**5 
fac = [1] + [0] * n
fac_inv = [1] + [0] * n
for i in range(1, n+1):
    fac[i] = fac[i-1] * (i) % MOD
    # Fermat's little theorem says
    # a**(p-1) mod p == 1
    # then, a * a**(p-2) mod p == 1
    # it means a**(p-2) is inverse element
    fac_inv[i] = fac_inv[i-1] * pow(i, MOD-2, MOD) % MOD

def mod_nCr(n, r):
    if n == 0 and r == 0:
        return 1
    if n < r or n < 0:
        return 0
    tmp = fac_inv[n-r] * fac_inv[r] % MOD
    return tmp * fac[n] % MOD 

total = 0
for i in range(M):
    total += (M - i) * N * N * mod_nCr(M * N - 2, K - 2) * i
    total %= MOD  
for i in range(N):
    total += (N - i) * M * M * mod_nCr(M * N - 2, K - 2) * i
    total %= MOD  
print(total)

### FIXED CODE ###

N, M, K = [int(item) for item in input().split()]
MOD = 10**9 + 7

n = 2 * 10**5 + 10
fac = [1] + [0] * n
fac_inv = [1] + [0] * n
for i in range(1, n+1):
    fac[i] = fac[i-1] * (i) % MOD
    # Fermat's little theorem says
    # a**(p-1) mod p == 1
    # then, a * a**(p-2) mod p == 1
    # it means a**(p-2) is inverse element
    fac_inv[i] = fac_inv[i-1] * pow(i, MOD-2, MOD) % MOD

def mod_nCr(n, r):
    if n == 0 and r == 0:
        return 1
    if n < r or n < 0:
        return 0
    tmp = fac_inv[n-r] * fac_inv[r] % MOD
    return tmp * fac[n] % MOD 

total = 0
for i in range(M):
    total += (M - i) * N * N * mod_nCr(M * N - 2, K - 2) * i
    total %= MOD  
for i in range(N):
    total += (N - i) * M * M * mod_nCr(M * N - 2, K - 2) * i
    total %= MOD  
print(total)
### BUGGY CODE ###

class Solution:

    def solve(self, N: int, M: int) -> int:

        mod = 10**9+7
        INT_MAX = 10**7

        # calculate {m+n}C{n}

        def egcd(a, b):
            if a == 0:
                return b, 0, 1
            else:
                g, y, x = egcd(b % a, a)
                return g, x - (b // a) * y, y

        def modinv(a, m):
            g, x, y = egcd(a, m)
            if g != 1:
                raise Exception('modular inverse does not exist')
            else:
                return x % m

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

        # prime list

        isPrime = [True] * (INT_MAX + 1)
        isPrime[0], isPrime[1] = False, False
        primes = []

        for i in range(2, len(isPrime)):
            if isPrime[i] == True:
                primes.append(i)
                for j in range(2 * i, len(isPrime), i):
                    isPrime[j] = False

        # solve

        m = M
        answer = 1
        factors = {}
        while m > 1:
            for p in primes:
                factors[p] = 0

                while m % p == 0:
                    m //= p
                    factors[p] += 1

                if factors[p] > 0:
                    answer *= combination(N + factors[p] - 1, N - 1, mod=mod)
                    answer %= mod

        return answer


if __name__ == '__main__':

    # standard input
    N, M = map(int, input().split())

    # solve
    solution = Solution()
    print(solution.solve(N, M))


### FIXED CODE ###

import math


class Solution:

    def solve(self, N: int, M: int) -> int:

        mod = 10**9+7
        INT_MAX = 10**9

        # calculate {m+n}C{n}

        def egcd(a, b):
            if a == 0:
                return b, 0, 1
            else:
                g, y, x = egcd(b % a, a)
                return g, x - (b // a) * y, y

        def modinv(a, m):
            g, x, y = egcd(a, m)
            if g != 1:
                raise Exception('modular inverse does not exist')
            else:
                return x % m

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

        # solve

        m = M
        answer = 1
        factors = {}
        for i in range(2, int(math.sqrt(M))+1):
            factor = 0
            while m % i == 0:
                m //= i
                factor += 1

            if factor > 0:
                answer *= combination(N + factor - 1, N - 1, mod=mod)
                answer %= mod

        if m > 1:
            answer *= N
            answer %= mod

        return answer


if __name__ == '__main__':

    # standard input
    N, M = map(int, input().split())

    # solve
    solution = Solution()
    print(solution.solve(N, M))
### BUGGY CODE ###

n, m = map(int, input().split())
p = [0] * m
y = [0] * m
dict = {}
for i in range(m):
    p[i], y[i] = map(int, input().split())

arr = [[] * n for i in range(n)]
for i in range(m):
    arr[p[i]-1].append(y[i])

for i in range(len(arr)):
    arr[i].sort()


for i in range(m):
    tmp = arr[p[i]-1]
    index = 1
    for j in range(len(tmp)):
        if tmp[j] == y[i]:
            break
        else:
            index += 1
    s_p = str(p[i]).zfill(6)
    y_p = str(index).zfill(6)
    print(s_p + y_p)


### FIXED CODE ###

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

arr = [[] for _ in range(n)] 

p = [0] * m
y = [0] * m

for i in range(m):
    p[i], y[i] = map(int, input().split())
    arr[p[i]-1].append(y[i])    

for i in range(n):
    arr[i].sort()

import bisect
for i in range(m):
    num = bisect.bisect_left(arr[p[i]-1], y[i]) + 1
    a = str(p[i])
    b = str(num)
    print(a.zfill(6) + b.zfill(6))
### BUGGY CODE ###

#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


def solve(S: str):
    N = len(S)

    U = [0]*(N+1)
    a = 0
    # for i in range(N-1, -1, -1):
    for i in range(N):
        a += (10**i)*int(S[N-1-i])
        a %= 2019
        U[i] = a
    # U = [int(S[i:]) % 2019 for i in range(N)] + [0]
    table = [0]*2019

    tot = 0
    # for i in range(N-1, -1, -1):
    for i in range(N):
        tot += table[U[N-1-i]]
        table[U[N-1-i]] += 1
    tot += table[0]
    print(tot)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = str(next(tokens))  # type: str
    solve(S)


if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


def solve(S: str):
    N = len(S)
    U = [0]*(N+1)
    a = 0
    beki = 1
    for i in range(N-1, -1, -1):
        a += beki*(ord(S[i])-ord("0"))
        a %= 2019
        beki = (beki*10) % 2019
        U[i] = a
    table = [0]*2019

    tot = 0
    for i in range(N-1, -1, -1):
        tot += table[U[i]]
        table[U[i]] += 1
    tot += table[0]
    print(tot)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = str(next(tokens))  # type: str
    solve(S)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

#python 3.5.2

N, M = [int(i) for i in input().split()]
As = [int(i) for i in input().split()]
choiced = [bc[1] for bc in [[int(j) for j in input().split()] for i in range(M)] for i in range(bc[0])]
choiced = choiced + As
choiced = sorted(choiced, reverse=True)
print(sum(choiced[:N]))

### FIXED CODE ###

#python 3.5.2

N, M = [int(i) for i in input().split()]
As = [int(i) for i in input().split()]
BCs = [[int(j) for j in input().split()] for i in range(M)]
BCs += [[1, a] for a in As]
BCs = sorted(BCs, key=lambda x: x[1], reverse=True)
cnt = 0
sum = 0
for b, c in BCs:
    if N < cnt + b:
        sum += (N - cnt)*c
        break
    else:
        sum += b*c
        cnt += b
print(sum)
### BUGGY CODE ###

import numpy as np
import time
import random
start = time.time()
#N=100000
N=int(input())
D=np.array(list(map(int,input().split())))
#D=np.concatenate([np.array([0]),np.array([random.randint(1,1000) for _ in range(99999)])])

#print(np.count_nonzero(D==0))
if D[0]!=0 or np.count_nonzero(D==0)!=1:
    print(0)
    exit()

k=max(D)


ans=1
past=1
for i in range(1,k+1):
    n=np.count_nonzero(D==i)
    if n==0:
        print(0)
        #ptime=time.time()-start
        #print(ptime)
        exit()
    ans*=past**n
    ans%=998244353
    past=n

print(ans)
#ptime=time.time()-start
#print(ptime)

### FIXED CODE ###

import collections
 
N=int(input())
D=list(map(int,input().split()))
 
c=collections.Counter(D)
 
max_D=max(D)
ans=1
previous_leaf=1
 
if D[0]!=0:
    ans=0
elif c[0]!=1:
    ans=0
else:
    for i in range(1,max_D+1):
        ans*=(previous_leaf**c[i])
        ans%=998244353
        previous_leaf=c[i]
 
print(ans)
### BUGGY CODE ###


S = input()
P = tuple(map(int, input().split()))

dis = abs(P[0]) + abs(P[1])
forward = S.count("F")

def add(p, d):
    return (p[0] + d[0], p[1] + d[1])

if dis > forward or (forward - dis) % 2 == 1:
    print("No")

else:
    now = {((0, 0), (1, 0), forward)} # (X, Y), dir
    for s in S:
        ne = set()
        for p, d, f in now:
            #Fのとき
            if s == "F":
                f -= 1
                p = add(p, d)
                dis = abs(P[0] - p[0]) + abs(P[1] - p[1])
                if dis <= forward:
                    ne = ne | {(p, d, f)}
            #Tのとき
            elif s == "T":
                ne = ne | {(p, (d[1], -d[0]), f), (p, (-d[1], d[0]), f) }
        now = ne
    
    for p,d,f in now:
        if p == P:
            print("Yes")
            break
    else:
        print("No")


### FIXED CODE ###

import bisect
import copy
import heapq
import sys
import itertools
import math
import queue
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]
def init_dp1(init, N): return [init for _ in range(N)]
def init_dp2(init, N, M): return [[init for _ in range(M)] for _ in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n) 


def main():
    S = input().strip()
    X, Y = read_values()
    F = list(map(len, S.split("T")))

    S = {F[0]}
    if len(F) >= 2:
        for x in F[2::2]:
            SS = set()
            for s in S:
                SS.add(s + x)
                SS.add(s - x)
            S = SS

    if not X in S:
        print("No")
        return
    
    S = {0}
    if len(F) >= 1:
        for x in F[1::2]:
            SS = set()
            for s in S:
                SS.add(s + x)
                SS.add(s - x)
            S = SS
    
    if not Y in S:
        print("No")
        return 
    
    print("Yes")


if __name__ == "__main__":
    main()
### BUGGY CODE ###

from sys import stdin
input = stdin.readline


def main():
  S = input()[:-1]
  dp = [[0]*13 for _ in range(len(S)+1)]
  dp[0][0] = 1

  for i in range(1, len(S)+1):
    if S[i-1] == '?':
      for s in range(10):
        for j in range(13):
          dp[i][(10*j + s) % 13] += dp[i-1][j]
    else:
      for j in range(13):
        dp[i][(10*j + int(S[i-1])) % 13] += dp[i-1][j]

  print(dp[len(S)][5] % 1_000_000_007)


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


### FIXED CODE ###

from sys import stdin
input = stdin.readline


def main():
  S = input()[:-1]
  dp = [[0]*13 for _ in range(len(S)+1)]
  dp[0][0] = 1

  MOD = 1_000_000_007
  for i in range(1, len(S)+1):
    if S[i-1] == '?':
      for s in range(10):
        for j in range(13):
          dp[i][(10*j + s) % 13] += (dp[i-1][j] % MOD)
    else:
      for j in range(13):
        dp[i][(10*j + int(S[i-1])) % 13] += (dp[i-1][j] % MOD)

  print(dp[len(S)][5] % MOD)


if(__name__ == '__main__'):
  main()
### BUGGY CODE ###

import numpy as np
N, M = map(int, input().split())
As = sorted(list(map(int, input().split())), reverse=True)
cards = np.array(As, dtype=np.int64) * -1

for i in range(M):
    B, C = map(int, input().split())

    p = np.searchsorted(cards, -C)
    if p >= N:
        continue

    replace = min(N - p, B)
    cards[p+replace:] = cards[p:N-replace]
    cards[p:p+replace] = -C

total = 0
for card in cards:
    total += -card
print(total)

### FIXED CODE ###

import heapq
from collections import defaultdict

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

As = map(int, input().split())
counts = defaultdict(int)
for A in As:
    counts[A] += 1
h = sorted(counts.keys())

for i in range(M):
    B, C = map(int, input().split())

    if C not in counts:
        heapq.heappush(h, C)
    counts[C] += B
    if len(h) > N:
        v = heapq.heappop(h)
        del counts[v]

total_count = 0
total = 0
for k in sorted(h, reverse=True):
    c = counts[k]
    c = min(c, N - total_count)
    total += k * c
    total_count += c
    if total_count > N:
        break
print(total)
### BUGGY CODE ###

import math
K = int(input())
list = []
for a in range(1,K+1):
    for b in range(1,K+1):
        for c in range(1,K+1):
           x = math.gcd(a,b)
           y = math.gcd(x,c)
           list.append(y)
print(sum(list))

### FIXED CODE ###

import math
k = int(input())
 
ans = 0
for i in range(1, k+1):
  for j in range(1, k+1):
    tmp = math.gcd(i,j)
    for l in range(1, k+1):
      ans += math.gcd(tmp, l)
print(ans)
### BUGGY CODE ###

n, m = list(map(int, input().split()))
city_nums = [[] for i in range(n)]
city_list = []
numbers = []

for i in range(m):
    pm, ym = list(map(int, input().split()))
    city_nums[pm-1].append(ym)
    city_list.append([pm,ym])
for i in range(n):
    city_nums[i].sort()
    
for i in range(m):
    cindex = city_nums[city_list[i][0]-1].index(city_list[i][1])
    
    print("{:0=6}{:0=6}".format(city_list[i][0], cindex+1))

### FIXED CODE ###

n, m = list(map(int, input().split()))
city_list = []

for i in range(m):
    pm, ym = list(map(int, input().split()))
    city_list.append([i,pm,ym])

city_count = {}
city = {}

for i,p,y in sorted(city_list, key=lambda x: x[2]):
    if not p in city_count:
        city_count[p] = 1
    else:
        city_count[p] += 1
    city[i,p] = city_count[p]

for i,p,y in city_list:
    print("{:0=6}{:0=6}".format(p, city[i,p]))
### BUGGY CODE ###

n, a, b = map(int,input().split())
mod = 10**9+7
total = pow(2, n, mod) - 1
def c(n, r):
    p, q = 1, 1
    for i in range(r):
        p *= (n-i)%mod
        q *= (i+1)%mod
    return p * pow(q, mod-2, mod)%mod

print((total - c(n, a) - c(n, b))%mod)

### FIXED CODE ###

import math
def f_pow(x,n):
    if n == 0:
        return 1
    half = f_pow(x, n//2)
    if n % 2:
        return x * half * half % mod
    else:
        return half * half % mod

def c(n, r):
    p,q = 1,1
    for i in range(r):
        p = p*(n-i)%mod
        q = q*(i+1)%mod
    return p * f_pow(q, mod-2)%mod

n,a,b = map(int,input().split())
mod = 10**9+7

s = f_pow(2, n) - 1
print((s - c(n,a) - c(n,b))%mod)
### BUGGY CODE ###

import numpy as np
n=int(input())
h=list(map(int,input().split()))
h=np.array(h)
ans=0
while True:
  for i in range(n):
    k=n-i
    cnt=0
    for j in range(1,k):
      if all(hh!=0 for hh in h[i:i+j+1]):
        cnt+=1
    h[i:i+cnt+1]=-1
    ans+=1
print(ans)

### FIXED CODE ###

n=int(input())
h=list(map(int,input().split()))
sum=h[0]
for i in range(n-1):
  if h[i+1]>h[i]:
    sum+=h[i+1]-h[i]
print(sum)
### BUGGY CODE ###

N, X, Y = map(int, input().split())
S = [[N]*N for _ in range(N)]

for i in range(N):
    S[i][i] = 0

    if i != N-1:
        S[i][i+1] = 1
        S[i+1][i] = 1

S[X-1][Y-1] = 1
S[Y-1][X-1] = 1

for _ in range(10):
    for i in range(N):
        for j in range(N):
            for k in range(N):
                S[i][j] = min(S[i][j], S[i][k]+S[k][j])

#print(S)

dist = [0]*N

from itertools import (
    accumulate,  # 累積和のイテレータ
    groupby,  # 値をkey,同じ値の集まりをgroup
    permutations,  # 順列
    combinations,  # 組み合わせ
    product,  # 重複あり順列（直積, 深いネストにも使える）
)

for i, j in combinations(list(range(N)), 2):
    d = S[i][j]
    dist[d] += 1

#print(dist)

for i in range(1, len(dist)):
    print(dist[i])

### FIXED CODE ###

N, X, Y = map(int, input().split())
S = [list(reversed(list(range(1, i+1)))) + list(range(N-i)) for i in range(N)]

S[X-1][Y-1] = 1
S[Y-1][X-1] = 1

for i in range(N):
    for j in range(N):
        x, y = X-1, Y-1
        S[i][j] = min(S[i][j], S[i][x]+1+S[y][j])

#print(S)

dist = [0]*N

from itertools import (
    accumulate,  # 累積和のイテレータ
    groupby,  # 値をkey,同じ値の集まりをgroup
    permutations,  # 順列
    combinations,  # 組み合わせ
    product,  # 重複あり順列（直積, 深いネストにも使える）
)

for i, j in combinations(list(range(N)), 2):
    d = S[i][j]
    dist[d] += 1

#print(dist)

for i in range(1, len(dist)):
    print(dist[i])
### BUGGY CODE ###

n,k = map(int,input().split())
p = list(map(int,input().split()))
kitaichi = []
for i in range(n):
    P = p[i]
    kitai = (((P*(P+1)/2))/P)
    kitaichi.append(kitai)
ans = 0
for j in range((n-k)+1):
    a = sum(kitaichi[j:j+k])
    if a > ans:
        ans = a
print(ans)


### FIXED CODE ###

n,k = map(int,input().split())
p = list(map(int,input().split()))
kitaichi = []
for i in range(n):
    P = p[i]
    kitai = 1+P
    kitaichi.append(kitai)
m = [0,]
a = 0
for j in range(n):
    a += kitaichi[j]
    m.append(a)
ans = 0
for l in range(n-k+1):
    temp = m[l+k]-m[l]
    if temp> ans:
      ans = temp
print(ans/2)
### BUGGY CODE ###

import sys
n = int(input())
command = sys.stdin.readlines()
Q = {}
for i in range(n):
    a,b = command[i].split()
    if a == "insert":
        Q[b] = 0
    else:
        if b in set(Q.keys()):
            print("yes")
        else:
            print("no")

### FIXED CODE ###

import sys
n = int(input())
dictionary = {}

k = sys.stdin.readlines()


for j in k:
    i = j.split()
    if i[0] == "insert":
        dictionary[i[1]] = 0
    else:
        if i[1] in dictionary:
            print("yes")
        else:
            print("no")
### BUGGY CODE ###

n = int(input())
l = sorted(list(map(int,input().split())))
 
count = 0 
 
for i in range(n - 2):
    for j in range(i+1,n-1):
        
        if l[i] + l[j] > l[n-1]:
            count += n-j-1
            
            continue
        
        low = j+1
        high = n-1
        
        while low < high:
            
            mid = (low + high)//2
            
            if l[i] + l[j] > l[mid]:
                
                low = mid +1
            
            else:    
                
                high = mid 
        else:
            
            count += low - j -1
print(count)            

### FIXED CODE ###

from bisect import bisect_left

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

L.sort()
result = 0
for i in range(N - 2):
    for j in range(i + 1, N - 1):
        result += bisect_left(L, L[i] + L[j]) - j - 1
print(result)
### BUGGY CODE ###

import numpy as np
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
dp=[np.inf]*n
dp[0]=0
dp[1]=abs(a[1]-a[0])
for i in range(2,n):
    for j in range(1,k+1):
        dp[i]=min(dp[i-j]+abs(a[i]-a[i-j]),dp[i])
print(dp[-1])

### FIXED CODE ###

n,k=map(int,input().split())
a=[int(i) for i in input().split()]
dp=[10**9]*n
dp[0]=0
dp[1]=abs(a[1]-a[0])
for i in range(2,n):
    for j in range(max(0,i-k),i):
        dp[i]=min(dp[j]+abs(a[i]-a[j]),dp[i])
print(dp[-1])
### BUGGY CODE ###

N = int(input())
A = [0] + [int(input()) for i in range(N)]
record = [0] * (N + 1)
loop = True
pushing = min(A[1:])
ans = -1
while loop:
    record[A[pushing]] += 1
    if record[2] == 1:
        ans = sum(record)
        loop = False
    if record.count(2) == True:
        loop = False
    pushing = A[pushing]
print(ans)

### FIXED CODE ###

def train(n):
    x =[0] + [int(input()) for i in range(n)]
    idx = 1
    for i in range(n+1):
        if x[idx] == 2:
            return i + 1
        idx = x[idx]
    return -1
n = int(input())
print(train(n))