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

n =int(input())
a = list()
 
for _ in range(n):
    a.append(int(input()))
 
b = sorted(a)
 
for i in range(n):
    if a[i] == max(a):
        print(b[-2]) 
    else:
        print(max(a))

### FIXED CODE ###

n =int(input())
a = list()
 
for _ in range(n):
    a.append(int(input()))
 
b = sorted(a)

 
for i in range(n):
    if a[i] == b[-1]:
        print(b[-2]) 
    else:
        print(b[-1])
### BUGGY CODE ###

import heapq

n,m,s,t = map(int, input().split())
L = [[int(x) for x in input().split()] for _ in range(m)]

cost = [[] for _ in range(n)]
for i in range(m):
    cost[L[i][0]-1].append(L[i][2:]+[L[i][1]-1])
    cost[L[i][1]-1].append(L[i][2:]+[L[i][0]-1])
    
def dijkstra(s, n, cost, c):
    d = [10**15]*n
    used = [0]*n
    d[s] = 0
    used[s] = 1
    edgelist = []
    for e in cost[s]:
        heapq.heappush(edgelist, [e[c], e[2]])
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        if used[minedge[1]] == 1:
            continue
        v = minedge[1]
        d[v] = minedge[0]
        used[v] = 1
        for e in cost[v]:
            if used[e[2]] == 0:
                heapq.heappush(edgelist, [e[c]+d[v], e[2]])
    return d

jpy = dijkstra(s-1, n, cost, 0)
snuuk = dijkstra(t-1, n, cost, 1)
ans_list = [0]*n
ans_list[n-1] = jpy[n-1]+snuuk[n-1]
for i in range(n-2, -1, -1):
    ans_list[i] = min(ans_list[i+1], jpy[i]+snuuk[i])
    
for i in range(n):
    print(10**15-ans_list[i])

### FIXED CODE ###

import heapq

n,m,s,t = map(int, input().split())
L = [[int(x) for x in input().split()] for _ in range(m)]

cost = [[] for _ in range(n)]
for i in range(m):
    cost[L[i][0]-1].append((L[i][2], L[i][3], L[i][1]-1))
    cost[L[i][1]-1].append((L[i][2], L[i][3], L[i][0]-1))
    
def dijkstra(s, n, cost, c):
    g = 10**6
    d = [10**15]*n
    used = [0]*n
    d[s] = 0
    used[s] = 1
    edgelist = []
    for e in cost[s]:
        heapq.heappush(edgelist, e[c]*g+e[2])
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        if used[minedge%g] == 1:
            continue
        v = minedge%g
        d[v] = minedge//g
        used[v] = 1
        for e in cost[v]:
            if used[e[2]] == 0:
                heapq.heappush(edgelist, (e[c]+d[v])*g + e[2])
    return d

jpy = dijkstra(s-1, n, cost, 0)
snuuk = dijkstra(t-1, n, cost, 1)
ans_list = [0]*n
ans_list[n-1] = jpy[n-1]+snuuk[n-1]
for i in range(n-2, -1, -1):
    ans_list[i] = min(ans_list[i+1], jpy[i]+snuuk[i])
    
for i in range(n):
    print(10**15-ans_list[i])
### BUGGY CODE ###

from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gcd
from operator import mul
from functools import reduce
from operator import mul
import pprint



sys.setrecursionlimit(2147483647)
INF = 100
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

n = I()
A = sorted(LI())
ans = 0
cnt = Counter(A)
B = [0] * (10 ** 6 + 1)
for a in A:
    if B[a] == 0 and cnt[a] == 1:
        ans += 1
    for i in range(a * 2, 10 ** 6 + 1, a):
        B[i] = 1


print(ans)





### FIXED CODE ###

from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gcd
from operator import mul
from functools import reduce
from operator import mul
import pprint



sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

n = I()
A = sorted(LI())
ans = 0
cnt = Counter(A)
m = max(A) + 1
B = [0] * (10 ** 6 + 1)
for a in A:
    if B[a] == 0 and cnt[a] == 1:
        ans += 1
    for i in range(a * 2, m, a):
        B[i] = 1


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

s = str(input())
t = str(input())

# pad a character to the first because i want to count index from 1
s = "." + s; t = "." + t;

a = len(s)
b = len(t)

dp = [['']*(b) for _ in range(a)]
# dp[i][j] is the length of lcs of s[0]s[1]...s[i] and t[0]t[1]...t[j]

for i in range(1, a):
    for j in range(1, b):
        if s[i] == t[j]:
            if len(dp[i][j]) < len(dp[i-1][j-1]) + 1:
                dp[i][j] = dp[i-1][j-1] + s[i]
        else:
            for adja in [[i-1, j-1], [i-1, j], [i, j-1]]:
                if len(dp[i][j]) < len(dp[adja[0]][adja[1]]):
                    dp[i][j] = dp[adja[0]][adja[1]]

print(dp[a-1][b-1])

### FIXED CODE ###

s = str(input())
t = str(input())

# pad a character to the first because i want to count index from 1
s = "." + s; t = "." + t;

a = len(s)
b = len(t)

dp = [['']*(b) for _ in range(2)]
# dp[i][j] is the length of lcs of s[0]s[1]...s[i] and t[0]t[1]...t[j]

for i in range(1, a):
    for j in range(1, b):
        if s[i] == t[j]:
            if len(dp[i&1][j]) < len(dp[(i+1)&1][j-1]) + 1:
                dp[i&1][j] = dp[(i+1)&1][j-1] + s[i]
        else:
            for adja in [[i-1, j-1], [i-1, j], [i, j-1]]:
                if len(dp[i&1][j]) < len(dp[adja[0]&1][adja[1]]):
                    dp[i&1][j] = dp[adja[0]&1][adja[1]]

print(dp[(a+1)&1][b-1])
### BUGGY CODE ###

N, M = map(int, input().split())
A = list(map(int, input().split()))
for _ in range(M):
    b, c = map(int, input().split())
    A += [c] * b

A.sort(reverse = True)

ans = 0
for i in range(N):
    ans += A[i]

print (ans)

### FIXED CODE ###

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

cb = []
for i in A:
    cb += [[i,1]]
for _ in range(M):
    b, c = map(int, input().split())
    cb += [[c, b]]
cb.sort(reverse = True)
#print (cb)

ans = 0
i = 0
j = 0
while i <= N:
    a = min(N-i, cb[j][1])
    ans += cb[j][0] * a
    j += 1
    i += a
    #print (ans)
    if i == N:
        print (ans)
        i += 1
### BUGGY CODE ###

# -*- coding: utf-8 -*-
# import math

def conbination(n, r):
    # return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
    if r == 0:
        return 1
    bunshi = 1
    for i in range(n, n-r, -1):
        bunshi *= i
    bunbo = 1
    for i in range(r, 0, -1):
        bunbo *= i
    return bunshi // bunbo

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

for i in range(1, K+1):
    c_blue = conbination(K-1, i-1)
    c_red = conbination(N-K+1, i)
    print((c_blue * c_red) % (10**9 + 7))


### FIXED CODE ###

# -*- coding: utf-8 -*-

def conbination(n, r):
    return f[n] // (f[r] * f[n-r])

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

f = [1]
for i in range(1, N+1):
    f.append(int(f[i-1]*i))

for i in range(1, K+1):
    if i > N-K+1:
        print(0)
        continue
    c_blue = conbination(K-1, i-1)
    c_red = conbination(N-K+1, i)
    print((c_blue * c_red) % (10**9 + 7))
### BUGGY CODE ###

from queue import deque

n, m = map(int, input().split())
links = [None] + [set() for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    links[a].add(b)
    links[b].add(a)

s = 1
t = links[s].pop()
visited = deque([s, t])
while True:
    s_remains = links[s].difference(visited)
    s_flag, t_flag = True, True
    if s_remains:
        s = s_remains.pop()
        visited.appendleft(s)
        s_flag = False
    t_remains = links[t].difference(visited)
    if t_remains:
        t = t_remains.pop()
        visited.append(t)
        t_flag = False
    if s_flag and t_flag:
        break
print(len(visited))
print(*visited)


### FIXED CODE ###

from queue import deque

n, m = map(int, input().split())
links = [None] + [set() for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    links[a].add(b)
    links[b].add(a)

s = 1
path = deque([s])
visited = {s}

while True:
    s_remains = links[s] - visited
    if s_remains:
        s = s_remains.pop()
        path.appendleft(s)
        visited.add(s)
    else:
        break

t = 1

while True:
    t_remains = links[t] - visited
    if t_remains:
        t = t_remains.pop()
        path.append(t)
        visited.add(t)
    else:
        break

print(len(path))
print(*path)
### BUGGY CODE ###

while 1:
    n,s=map(int,input().split())
    if not n:break
    a=sorted([int(input()) for _ in range(n)],reverse=1)
    b=0
    for i in range(n):
        for j in range(i+1,n):
            if a[i]+a[j]>s:b+=1
            else:break
        if a[i]+a[j]<=s:break
    print(b)

### FIXED CODE ###

while 1:
    n,s=map(int,input().split())
    if n==0:break
    r=[0]*101
    for _ in [0]*n:r[int(input())]+=1
    a=0
    for i in range(101):
        if i*2>s:a+=(r[i]**2-r[i])//2
        a+=r[i]*sum(r[j] for j in range(max(i+1,s+1-i),101))
    print(a)
### BUGGY CODE ###

n = int(input())
x = input()
for i in range(n):
    t = x[:i] + ('0' if x[i] == '1' else '1') + x[i + 1:]
    ans = 0
    while int(t, 2) > 0:
        t = bin(int(t, 2) % (t.count('1')))[2:]
        ans += 1
    print(ans)

### FIXED CODE ###

n = int(input())
x = input()
count_1 = x.count('1')
value = [0, 0]
x_int = int(x, 2)
value[0] = x_int % (count_1 - 1) if count_1 > 1 else 0
value[1] = x_int % (count_1 + 1)
for i in range(n):
    if x[i] == '0':
        tmp = (pow(2, n - i - 1, count_1 + 1) + value[1]) % (count_1 + 1)
    else:
        if count_1 == 1:
            print(0)
            continue
        tmp = (-pow(2, n - i - 1, count_1 - 1) + value[0]) % (count_1 - 1)
    ans = 1
    while tmp > 0:
        tmp = tmp % (bin(tmp).count('1'))
        ans += 1
    print(ans)
### BUGGY CODE ###

# coding: utf-8
a, b, x = map(int, input().split())
cnt = 0
n = b - a + 1
for i in range(n):
    if (a+i)%x==0:
        cnt += 1
print(cnt)

### FIXED CODE ###

# coding: utf-8
a, b, x = map(int, input().split())
f_a = (a-1)//x + 1 if a>=1 else 0
f_b = b//x + 1
print(f_b - f_a)
### BUGGY CODE ###

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

C = list(set(A))

B = len(C)

x = B - K #種類の差

ans = 0

figure_list = [0] * B

if x<=0:
    print('0')
else:
    for i in range(B):
        stock = int(C[i])
        counter = 0
        for ii in range(N):
            if stock == A[ii]:
                counter += 1
        figure_list[i] = counter

    figure_list = sorted(figure_list)

    for i in range(B-K):
        ans += figure_list[i]

    print(ans)    





### FIXED CODE ###


#【註】N 個のボールと K 種類の整数
N, K = map(int, input().split())

#【註】ボールに書かれている数 A_1...A_N
A = list(map(int, input().split()))

#【註】何種類あるか？を set で取得
C = list(set(A))

# 数字の種類数
B = len(C) 
# 元々の種類と目的の種類の差
x = B - K

#-----
#【註】「文字：回数」という辞書を使って、ループを最小限にします。
d = {}

#【解説】A のそれぞれの要素について
for i in A:
    #【解説】もし辞書に既に登録されていれば、その値（出現回数）に 1 を足す
    if i in d:
        d[i] += 1
    #【解説】そうでなければ、辞書にキーを登録して値（出現回数）を 1 にする
    else:
        d[i] = 1

#【解説】辞書を値でソートすると、出現回数が小さい順に並ぶ
d = sorted(d.items(), key=lambda x:x[1])

ans = 0
count = 0

if x<=0:
    print('0')
else:
    #【解説】辞書からキーと値を取り出し
    for key, value in d:
        #【解説】取り出した玉の数に value を足す
        ans = ans + value
        #【解説】何種類取り出したか、の値に 1 を足す
        count = count + 1

        #【解説】もし x 種類取り出しが完了したら ans を出力
        if count == x:
            print(ans)
            break
### BUGGY CODE ###

#K : XYZそれぞれは、0以上K以下
#S : X+Y+Zの合計値を示すS

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

X=Y=Z=0
result = 0
while(X<=S and X<=K):
    while(X+Y<=S and Y<=K):
        if 0 <= S-X-Y <=K:
            result +=1
        # Z = S-X-Y
        # # print("XYZ",X,Y,Z)
        # if X+Y+Z == S:
        #     if  Z<=K :
        #         result+=1 
        Y+=1
    Y=0
    X+=1

print(result)

### FIXED CODE ###

#K : XYZそれぞれは、0以上K以下
#S : X+Y+Zの合計値を示すS

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

X=Y=Z=0
result = 0
for x in range(K+1):
    for y in range ( K+1 ):
        if 0 <= S-X-Y <=K:
            result +=1
        # Z = S-X-Y
        # # print("XYZ",X,Y,Z)
        # if X+Y+Z == S:
        #     if  Z<=K :
        #         result+=1 
        Y+=1
    Y=0
    X+=1

print(result)
### BUGGY CODE ###

from collections import deque
import sys
input = sys.stdin.readline
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch-=1; cw-=1; dh-=1; dw-=1
area = [list(input()) for _ in range(h)]
inf = 10**100
dist = [[inf]*w for i in range(h)]

dwalk = [(0, 1), (0, -1), (1, 0), (-1, 0)]

def Dijkstra(ch, cw):
    import heapq
    edgelist = [(0, ch, cw)]
    heapq.heapify(edgelist)
    dist[ch][cw] = 0
    while len(edgelist):
        cost, y, x = heapq.heappop(edgelist)
        if y==dh and x==dw:
            return dist
        for next_y, next_x in dwalk:
            if 0<=y+next_y<h and 0<=x+next_x<w:
                if area[y+next_y][x+next_x]=='#': continue
                if dist[y+next_y][x+next_x]>cost:
                    dist[y+next_y][x+next_x] = cost
                    heapq.heappush(edgelist, (cost, y+next_y, x+next_x))
        for next_y in range(-2, 3):
            for next_x in range(-2, 3):
                    if 0<=y+next_y<h and 0<=x+next_x<w:
                        if area[y+next_y][x+next_x]=='#': continue
                        if dist[y+next_y][x+next_x]>cost+1:
                            dist[y+next_y][x+next_x] = cost+1
                            heapq.heappush(edgelist, (cost+1, y+next_y, x+next_x))
    return dist

dist = Dijkstra(ch, cw)
if dist[dh][dw] == inf:
    print(-1)
else:
    print(dist[dh][dw])

### FIXED CODE ###

from collections import deque
import sys
input = sys.stdin.readline
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch-=1; cw-=1; dh-=1; dw-=1
area = [list(input()) for _ in range(h)]
inf = 10**100
dist = [[inf]*w for i in range(h)]

dwalk = [(0, 1), (0, -1), (1, 0), (-1, 0)]

def Dijkstra(ch, cw):
    import heapq
    edgelist = [(0, ch, cw)]
    heapq.heapify(edgelist)
    dist[ch][cw] = 0
    while len(edgelist):
        cost, y, x = heapq.heappop(edgelist)
        if y==dh and x==dw:
            return dist
        if dist[y][x] < cost: continue
        for next_y, next_x in dwalk:
            if 0<=y+next_y<h and 0<=x+next_x<w:
                if area[y+next_y][x+next_x]=='#': continue
                if dist[y+next_y][x+next_x]>cost:
                    dist[y+next_y][x+next_x] = cost
                    heapq.heappush(edgelist, (cost, y+next_y, x+next_x))
        for next_y in range(-2, 3):
            for next_x in range(-2, 3):
                    if 0<=y+next_y<h and 0<=x+next_x<w:
                        if area[y+next_y][x+next_x]=='#': continue
                        if dist[y+next_y][x+next_x]>cost+1:
                            dist[y+next_y][x+next_x] = cost+1
                            heapq.heappush(edgelist, (cost+1, y+next_y, x+next_x))
    return dist

dist = Dijkstra(ch, cw)
if dist[dh][dw] == inf:
    print(-1)
else:
    print(dist[dh][dw])
### BUGGY CODE ###

n = int(input())
a=[]
for i in range(n):
    a.append(input())


a_f = list(set(a))
num = []


for i in a_f: 
    num.append(a.count(i))
    
result=[]
    
for n, i in enumerate(num):
    if i == max(num):
        result.append(a_f[n])
        
a_i=sorted(result)

for i in a_i:
    print(i)

### FIXED CODE ###

n = int(input())
l=[]
for i in range(n):
    l.append(input())
from collections import Counter
S=Counter(l)#カウンタークラスが作られる。S=Counter({'b': 5, 'c': 4, 'a': 3})

mn = max(S.values())
for letter, count in sorted(S.most_common()):
    if(count==mn):
        print(letter)
### BUGGY CODE ###

def main():
    from collections import deque
    import sys
    def input():
        return sys.stdin.readline()[:-1]
    S=input()
    Q=int(input())
    A=[input().split() for _ in range(Q)]
    d=deque(S)
    d_re=d.reverse
    d_left=d.appendleft
    d_right=d.append
    for x in A:
        if x[0]=="1":
            d_re()
        else:
            if x[1]=="1":
                d_left(x[2])
            else:
                d_right(x[2])

    print("".join(d))    

if __name__ == '__main__':
    main()


### FIXED CODE ###

def main():
    from collections import deque
    import sys
    def input():
        return sys.stdin.readline()[:-1]
    S=input()
    Q=int(input())
    A=[input().split() for _ in range(Q)]
    d=deque(S)
    
    d_left=d.appendleft
    d_right=d.append
    j=["1","2"]
    k=0
    j_re=j.reverse
    for x in A:
        if x[0]=="1":
            j_re()
            k+=1
        else:
            if x[1]==j[0]:
                d_left(x[2])
            else:
                d_right(x[2])
    if k%2==1:
        d.reverse()
    print("".join(d))    

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

from collections import deque

h, w = map(int, input().split())
c = [list(input()) for _ in range(h)]

q = deque([])

for i in range(h):
    for j in range(w):
        if c[i][j] == '#':
            q.append([i, j])
            c[i][j] = 0

p = q.popleft()
max = 0
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
while True:
    xx = p[0]
    yy = p[1]
    for i in range(4):
        x = xx + dx[i]
        y = yy + dy[i]
        if x < 0 or x > h - 1 or y < 0 or w - 1 < y:
            continue
        if c[x][y] == '.':
            q.append([x, y])
            count = c[xx][yy] + 1
            if max < count:
                max = count
            c[x][y] = count
    if len(q) == 0:
        break
    p = q.popleft()
print(max)


### FIXED CODE ###

from collections import deque

h, w = map(int, input().split())
c = [list(input()) for _ in range(h)]

q = deque([])

for i in range(h):
    for j in range(w):
        if c[i][j] == '#':
            q.append([i, j])
            c[i][j] = 0

p = q.popleft()
max = 0
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
while True:
    xx = p[0]
    yy = p[1]
    for i in range(4):
        x = xx + dx[i]
        y = yy + dy[i]
        if x < 0 or x > h - 1 or y < 0 or w - 1 < y:
            continue
        if c[x][y] == '.':
            q.append([x, y])
            count = c[xx][yy] + 1
            if max < count:
                max = count
            c[x][y] = count
    if len(q) == 0:
        break
    p = q.popleft()
print(max)
### BUGGY CODE ###

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

a = 0
b = 0
ans = 0
for k in range(len(A)):
    a += A[k]
    A[k] = a
for k in range(len(B)):
    b += B[k]
    B[k] = b

AA = [0] + A

BB = [0] + B

for k in range(N+1):
    if AA[k] <= K:
        for j in range(M+1):
            if  K >= AA[k] + BB[j]:
                ans = max(k+j, ans)
                continue
            else:
                break
    else:
        break
print(ans)

 

### FIXED CODE ###

N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
a, b = [0], [0]
for i in range(N):
  a.append(a[i] + A[i])
for i in range(M):
  b.append(b[i] + B[i])
ans, j = 0, M
for i in range(N + 1):
  if a[i] > K:
    break
  while b[j] > K - a[i]:
    j -= 1
  ans = max(ans, i + j)
print(ans)
### BUGGY CODE ###

from collections import deque
import copy

# グラフの作成(無向グラフでは#を消す)
n, q = map(int, input().split())
graph = [deque([]) for _ in range(n+1)]
for _ in range(n-1):
    a, b  = [int(x) for x in input().split()]
    graph[a].append(b)
    graph[b].append(a) # 無向グラフ
#print(graph)
#q_list = [list(map(int, input().split())) for _ in range(q)]
q_sum_list = [0 for _ in range(n)]
for i in range(q):
    p, x = map(int, input().split())
    q_sum_list[p-1] += x
#print(q_sum_list)
#arrive_rireki = [-1] * (N + 1)

ans = [0]*n
score = [0]*n

# 深さ優先探索
def dfs(v):
    arrive_rireki = [-1] * (n + 1)
    #print("check", graph_temp, arrive_rireki) #deepcopy の確認
    stack = [v]
    arrive_rireki[v] = 1
    while stack:
        #print("stack", stack)
        v = stack[-1]
        if graph[v]:
            w = graph[v].popleft()
            if arrive_rireki[w] < 0:
                arrive_rireki[w] = 1
                stack.append(w)
        else:
            stack.pop()
            #print("stack pop", v, stack)
            score[v-1] += q_sum_list[v-1]
            for i in range(len(stack)):
                score[v-1] += q_sum_list[stack[i]-1]
                #print(score, q_sum_list[stack[i]-1])
    return score

dfs(1)
#print(eda_list)
print(* score)


### FIXED CODE ###

from collections import deque
import copy

# グラフの作成(無向グラフでは#を消す)
n, q = map(int, input().split())
graph = [deque([]) for _ in range(n+1)]
for _ in range(n-1):
    a, b  = [int(x) for x in input().split()]
    graph[a].append(b)
    graph[b].append(a) # 無向グラフ
#print(graph)
q_sum_list = [0 for _ in range(n)]
for i in range(q):
    p, x = map(int, input().split())
    q_sum_list[p-1] += x
#print(q_sum_list)
arrive_rireki = [-1] * (n + 1)

score = [0]*n
score_temp = 0

# 深さ優先探索
def dfs(v):
    global score_temp
    #arrive_rireki = [-1] * (n + 1)
    #print("check", graph_temp, arrive_rireki) #deepcopy の確認
    stack = [v]
    arrive_rireki[v] = 1
    score_temp += q_sum_list[v-1]
    while stack:
        #print("stack", stack)
        v = stack[-1]
        if graph[v]:
            w = graph[v].popleft()
            if arrive_rireki[w] < 0:
                arrive_rireki[w] = 1
                stack.append(w)
                score_temp += q_sum_list[w-1]
        else:
            stack.pop()
            #score[v-1] += q_sum_list[v-1]
            score[v-1] = score_temp
            score_temp -= q_sum_list[v-1]
            #print("stack pop", v, stack)
            #for i in range(len(stack)):
            #    score[v-1] += q_sum_list[stack[i]-1]
                #print(score, q_sum_list[stack[i]-1])
    return score

dfs(1)
#print(eda_list)
print(* score)
### BUGGY CODE ###

n = int(input())
r =[]
for i in range(n):
    r.append(int(input()))

max_value = -10**9
for i in range(n):
    for j in range(i+1,n):
        if r[j] - r[i] > max_value:
            max_value = r[j] - r[i]
print(max_value)


### FIXED CODE ###

n = int(input())
max_value = -10**9
min_value = int(input())
for i in range(1,n):
    r = int(input())
    max_value = max(max_value,r-min_value)
    min_value = min(min_value, r)

print(max_value)
### BUGGY CODE ###

n = int(input())
a = [int(input()) for i in range(n)]
i = 0
cnt = 1
while a[i]!=2:
    t = a[i]
    if i == a[t-1]-1:
        print(-1)
        exit()
    i = t-1
    cnt += 1
else:
    print(cnt)

### FIXED CODE ###

n = int(input())
a = [int(input()) for i in range(n)]
cnt = 0
tmp = 0
for i in range(n):
    if a[tmp]==2:
        print(cnt+1)
        exit()
    else:
        tmp =a[tmp]-1
        cnt += 1
else:
    print(-1)
    exit()