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

class BIT:
    def __init__(self,n):
        self.size=n
        self.tree=[0]*-~n
    def sum(self,i):
        s=0
        while i:
            s+=self.tree[i]
            i-=i&-i
        return s
    def add(self,i,x):
        while i<=self.size:
            self.tree[i]+=x
            i+=i&-i
def main():
    n,*a=map(int,open(0).read().split())
    m=n*-~n//2+1>>1
    ng=max(a)+1
    ok=0
    while ng-ok>1:
        mid=(ok+ng)//2
        b=BIT(n-~n)
        badd,bsum=b.add,b.sum
        c=n+1
        s=0
        badd(c,1)
        for t in a:
            c+=1if t>=mid else-1
            s+=bsum(c)
            badd(c,1)
        if s>=m:ok=mid
        else:ng=mid
    print(ok)
main()

### FIXED CODE ###

class BIT:
    def __init__(self,n):
        self.size=n
        self.tree=[0]*-~n
    def sum(self,i):
        s=0
        while i:
            s+=self.tree[i]
            i-=i&-i
        return s
    def add(self,i,x):
        while i<=self.size:
            self.tree[i]+=x
            i+=i&-i
n,*a=map(int,open(0).read().split())
m=n*-~n//2+1>>1
ng=max(a)+1
ok=0
while ng-ok>1:
    mid=(ok+ng)//2
    b=BIT(n-~n)
    c=n+1
    s=0
    b.add(c,1)
    for t in a:
        c+=1if t>=mid else-1
        s+=b.sum(c)
        b.add(c,1)
    if s>=m:ok=mid
    else:ng=mid
print(ok)
### BUGGY CODE ###

N = int(input())
T = [0]*100000
X= [0]*100000
Y= [0]*100000
x = 0
y = 0

for n in range(N):
        T[n],X[n],Y[n] = (map(int, input().split()))

flag = 1
for n in range(N):
    #print(n)
    if flag == 0:
        continue


    if n == 0:
        count = T[n]
    else:
        count = T[n] - T[n-1]
        x = X[n-1]
        y = Y[n-1]
    c = 0
    end = 0
    while True:
        if end == 1:
            break
        s_x = X[n] - x
        s_y = Y[n] - y
        #print(str(x)+' '+str(y))

        if ((s_x >= 0 or s_y >= 0) )and (c!=count):
            if s_x >0:
                x +=1
                c += 1
            elif s_x < 0:
                x -= 1
                c+=1
            elif s_y > 0:
                y +=1
                c += 1
            elif s_y < 0:
                y -= 1
                c+=1
            elif s_x==0:
                x +=1
                c +=1
        elif c==count:
            if (x == X[n] and y ==Y[n]):
                flag = 1
                end=1
            else:
                flag=0
                end =1
    


if flag == 1:
    print('Yes')
else:
    print('No')


### FIXED CODE ###

N = int(input())
T = [0]*100000
X= [0]*100000
Y= [0]*100000
x = 0
y = 0

for n in range(N):
        T[n],X[n],Y[n] = (map(int, input().split()))

flag = 1
for n in range(N):
    #print(n)
    if flag == 0:
        continue


    if n == 0:
        count = T[n]
    else:
        count = T[n] - T[n-1]
        x = X[n-1]
        y = Y[n-1]
    c = 0
    end = 0
    while True:
        if end == 1:
            break
        s_x = X[n] - x
        s_y = Y[n] - y
    #    print(str(s_x)+' '+str(s_y))

        if ((s_x != 0 or s_y !=0) )and (c!=count):
            if s_x >0:
                x +=1
                c += 1
            elif s_x < 0:
                x -= 1
                c+=1
            elif s_y > 0:
                y +=1
                c += 1
            elif s_y < 0:
                y -= 1
                c+=1
        elif  ((s_x == 0 and s_y == 0) )and (c!=count):
                x +=1
                c +=1
        elif c==count:
            if (x == X[n] and y ==Y[n]):
                flag = 1
                end=1
            else:
                flag=0
                end =1



if flag == 1:
    print('Yes')
else:
    print('No')
### BUGGY CODE ###

import math
import numpy as np

N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
for i in range(len(P)): #Pの中身は次の動く先の位置なのでデクリメントする
    P[i] -= 1

ans = -99999999999999

for i in range(N):
    x = i
    total = 0
    s=[]
    while(1):#サイクルごとに長さをまず求める，
        x = P[x]
        s.append(C[x])
        total += C[x]
        if x == i:
            break
    l = len(s)#サイクルの長さ
    t = 0
    for i in range(l):#サイクルの中でどこで終わるのがベストか探す
        t += s[i]
        if i+1> K:#Kがサイクルより短かったらそこで終わる
            break
        now = t
        if total > 0:
            cycle = int((K-i-1)/l)
            now += total*cycle

        ans = max(ans, now)

print(ans)


### FIXED CODE ###

#import math
#import numpy as np

N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
#for i in range(len(P)): #Pの中身は次の動く先の位置なのでデクリメントする
#    P[i] -= 1

ans = -99999999999999

for i in range(N):
    x = i
    total = 0
    s=[]
    while(1):#サイクルごとに長さをまず求める，
        x = P[x]-1
        s.append(C[x])
        total += C[x]
        if x == i:
            break
    l = len(s)#サイクルの長さ
    t = 0
    for i in range(l):#サイクルの中でどこで終わるのがベストか探す
        t += s[i]
        if i+1> K:#Kがサイクルより短かったらそこで終わる
            break
        now = t
        if total > 0:
            cycle = int((K-i-1)/l)
            now += total*cycle

        ans = max(ans, now)

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

# DP
N, M = map(int, input().split())
broken = [int(input()) for _ in range(M)]

MOD = 10**9+7
dp = [0 for i in range(N+2)]
dp[N] = 1

for i in reversed(range(N)):
    if i in broken:
        continue
    dp[i] = (dp[i+1] + dp[i+2]) % MOD

print(dp[0])


### FIXED CODE ###

N, B = map(int, input().split())
ana = []
dp = [0] * (N+2)

for i in range(B):
    ana.append(int(input()))

mod = 1000000007

dp[N] = 1
for i in reversed(range(N)):
    if len(ana) >= 1 and i == ana[-1]:
        dp[i] = 0
        if len(ana) != 0:
            ana.pop(-1)
        continue
    dp[i] = dp[i + 1] + dp[i + 2]
print(dp[0] % mod)
### BUGGY CODE ###

def check(list_a, a):
    if a in list_a:
        list_a.remove(a)
        return False
    else:
        return True

N = input()
D = [int(i) for i in input().split(" ")]
M = input()
T = ["NO" for i in input().split() if check(D,int(i))]
if T:
    print("NO")
else:
    print("YES")

### FIXED CODE ###

from collections import Counter
N = input()
D = Counter([i for i in input().split()])
M = input()
T = Counter([i for i in input().split()])
for key, value in T.items():
    try:
        if D[key] < value:
            print("NO")
            break
    except:
        print("NO")
        break
else:
    print("YES")
### BUGGY CODE ###

#入力
h,w=map(int,input().split())
ch,cw=map(int,input().split())
dh,dw=map(int,input().split())
s=[input() for i in range(h)]

#for i in range(h):
#  s_=list(input())
#  s.append(s_)
#幅優先探索
from collections import deque
q=deque([(ch-1,cw-1)])
used=[[float("INF")]*w for i in range(h)]
used[ch-1][cw-1]=0
X=((-1,0),(1,0),(0,1),(0,-1))
Y=((-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),(-1,-2),(-1,-1),(-1,1),(-1,2),(0,-2),(0,1),(0,2),(1,-2),(1,-1),(1,1),(1,2),(2,-2),(2,-1),(2,0),(2,1),(2,2))
while len(q)>0:
  y,x=q.popleft()
  for dy,dx in X:
    nx=x+dx
    ny=y+dy
    if nx>=0 and nx<w and ny>=0 and ny<h and s[ny][nx]==".":
      if used[ny][nx]>used[y][x]:
        used[ny][nx]=used[y][x]
        q.appendleft((ny,nx))
  for dy,dx in Y:
    nx=x+dx
    ny=y+dy
    if nx>=0 and nx<w and ny>=0 and ny<h and s[ny][nx]==".":
      if used[ny][nx]>used[y][x]:
        used[ny][nx]=used[y][x]+1
        q.append((ny,nx))

if used[dh-1][dw-1]==float("INF"):
  print(-1)
else:
  print(used[dh-1][dw-1])

      
      
      
    
  
  


### FIXED CODE ###

#入力
h,w=map(int,input().split())
ch,cw=map(int,input().split())
dh,dw=map(int,input().split())
from sys import stdin
s=[stdin.readline() for i in range(h)]

#for i in range(h):
#  s_=list(input())
#  s.append(s_)
#幅優先探索
from collections import deque
q=deque([(ch-1,cw-1)])
used=[[float("INF")]*w for i in range(h)]
used[ch-1][cw-1]=0
X=((-1,0),(1,0),(0,1),(0,-1))
Y=((-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),(-1,-2),(-1,-1),(-1,1),(-1,2),(0,-2),(0,1),(0,2),(1,-2),(1,-1),(1,1),(1,2),(2,-2),(2,-1),(2,0),(2,1),(2,2))
while len(q)>0:
  y,x=q.popleft()
  for dy,dx in X:
    nx=x+dx
    ny=y+dy
    if nx>=0 and nx<w and ny>=0 and ny<h and s[ny][nx]==".":
      if used[ny][nx]>used[y][x]:
        used[ny][nx]=used[y][x]
        q.appendleft((ny,nx))
  for dy,dx in Y:
    nx=x+dx
    ny=y+dy
    if nx>=0 and nx<w and ny>=0 and ny<h and s[ny][nx]==".":
      if used[ny][nx]>used[y][x]:
        used[ny][nx]=used[y][x]+1
        q.append((ny,nx))

if used[dh-1][dw-1]==float("INF"):
  print(-1)
else:
  print(used[dh-1][dw-1])
### BUGGY CODE ###

import heapq
def SME(start,end):
    if end > N : end = N
    count = 0
    for i,x in enumerate(Whole[start:end]):
        heapq.heappush(A,[x,i])
    for j in range(start,end):
        a = heapq.heappop(A)
        if None not in ANS[a[1]:a[1]+L] : continue
        for i in range(L):
            idx = a[1] + i
            try :
                if ANS[idx] : continue
                else :
                    ANS[idx] = a[0]
                    count += 1
            except IndexError : continue
        if count > N * parameter : break
    for i in range(L):
        if ANS[i] : continue
        else : ANS[i] = min(Whole[:i+1])
    for i in range(L,N):
        if ANS[i] : continue
        else : ANS[i] = min(Whole[i+1-L:i+1])
    return ANS
[N,L] = [int(x) for x in input().split()]
Whole = [int(x) for x in input().split()]
A = []
parameter = 0.9995
ANS = [None]*N
ANS = SME(0, N)
for i in ANS[L-1:-1]:print(i, end=" ")
print(ANS[-1])

### FIXED CODE ###

def ascend(a,b):
    mini = min(A[a:a+L])
    ans[a] = mini
    for i in range(a+1,b):
        if A[i+L-1] <= mini : mini = A[i+L-1]
        elif A[i-1] == mini : mini = min(A[i:i+L])
        ans[i] = mini

def descend(a,b):
    mini = min(A[b-1:b+L-1])
    ans[b-1] = mini
    for i in range(b-2,a-1,-1):
        if A[i] <= mini : mini = A[i]
        elif A[i+L] == mini: mini = min(A[i:i+L])
        ans[i] = mini
    
[N,L] = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
ans = [None]*(N-L+1)
count = 0;
if N > 10 ** 4:
    for i in range(100):
        if A[i+1] > A[i] : count += 1
    if count > 80 : descend(0, N-L+1)
    else : ascend(0,N-L+1)
else :
    ascend(0, N-L+1)
for i in ans[:-1] : print(i, end=" ")
print(ans[-1])
### BUGGY CODE ###

from functools import reduce

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

def prime_factorize(n):
    res = []
    while n % 2 == 0:
        res.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            res.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        res.append(n)
    return res

def is_pairwise_coprime():
    s = set()
    for ai in a:
        p = set(prime_factorize(ai))
        ns = s | p
        if len(s) + len(p) != len(ns):
            return False
        s = ns
    return True

def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

def is_setwise_coprime():
    return reduce(gcd, a) == 1


if is_pairwise_coprime():
    print('pairwise coprime')
elif is_setwise_coprime():
    print('setwise coprime')
else:
    print('not coprime')

### FIXED CODE ###

from functools import reduce

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

m = max(a)
d = [0] * (m + 1)
d[1] = 1
for i in range(2, m + 1):
    for j in range(i, m + 1, i):
        if d[j] == 0:
            d[j] = i

def prime_factorize(n):
    res = []
    if n == 1:
        return res
    while n > 1:
        res.append(d[n])
        n //= d[n]
    return res

def is_pairwise_coprime():
    exists = [0] * (m + 1)
    for ai in a:
        for p in set(prime_factorize(ai)):
            if exists[p]:
                return False
            exists[p] = 1
    return True

def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

def is_setwise_coprime():
    return reduce(gcd, a) == 1


if is_pairwise_coprime():
    print('pairwise coprime')
elif is_setwise_coprime():
    print('setwise coprime')
else:
    print('not coprime')
### BUGGY CODE ###

import math
def GCD(a,N):
    gcd = a[0]
    for i in range(1, N):
        gcd = math.gcd(gcd, a[i])
    return gcd


k = int(input())
# h, w = map(int, input().split())
# a = list(map(int, input().split()))
ans = 0
L = []
for i in range(1, k+1):
    for j in range(1, k+1):
        for l in range(1, k+1):
            if i==1 or j==1 or l==1:
                ans += 1
            else:
                ans += GCD([i,j,l], 3)

print(ans)

### FIXED CODE ###

from math import gcd

# def GCD(a,N):
#     gcd = a[0]
#     for i in range(1, N):
#         gcd = math.gcd(gcd, a[i])
#     return gcd


k = int(input())

ans = 0
L = []
G = [0] * k**3

for i in range(1, k+1):
    for j in range(1, k+1):
        for l in range(1, k+1):
            # _l = sorted([i,j,l])
            # if i==1 or j == 1 or l == 1:
            #     ans += 1
            # elif not _l in L:
            #     L.append(_l)
            #     g = GCD(_l, 3)
            #     G[L.index(_l)] = g
            #     ans += g
            # else:
            #     ans += G[L.index(_l)]
            ans += gcd(i,gcd(j,l))

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

N = int(input())
A = list([int(input()) for _ in range(N)])

p = []
for a in A:
    if a in set(p):
        p.remove(a)
    else:
        p.append(a)

print(len(p))

### FIXED CODE ###

import collections

N = int(input())
A = [int(input()) for _ in range(N)]
A = collections.Counter(A)

cnt = 0
for key, value in A.items():
    if value % 2 == 0:
        pass
    else:
        cnt += 1

print(cnt)
### BUGGY CODE ###

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

for i in range(N):
    if (i < N-1 and A[i] == A[i+1]) or (0 < i and A[i-1] == A[i]):
        ans += 1
        continue
    border = A[i] // 2
    for j in range(i):
        if A[i] % A[j] == 0:
            ans += 1
            break
        elif A[j] > border:
            break

print(N - ans)

### FIXED CODE ###

N = int(input())
A = sorted(list(map(int, input().split())))
if N == 1:
    print(1)
elif A[0] == 1 and A[1] == 1:
    print(0)
elif A[0] == 1:
    print(1)
else:
    Eratos = [False]*1000001
    ans = 0
    for i in range(N):
        if Eratos[A[i]]:
            ans += 1
        else:
            if i < N-1 and A[i] == A[i+1]:
                ans += 1
            for j in range(A[i], 1000001, A[i]):
                Eratos[j] = True
    print(N-ans)
### BUGGY CODE ###

n = int(input())
s = list(input())

cnt = []
for i in range(n):
    cnt.append(0)
    for j in range(n):
        if i < j:
            if s[j] == 'E':
                cnt[i] += 1
        elif i > j:
            if s[j] == 'W':
                cnt[i] += 1

print(min(cnt))

### FIXED CODE ###

n = int(input())
s = list(input())

l = [0]
r = [0]
l_cnt = 0
r_cnt = 0
for i in range(n-1):
    if s[i] == 'W':
        l_cnt += 1
    if s[n-i-1] == 'E':
        r_cnt += 1
    l.append(l_cnt)
    r.append(r_cnt)
print(min(l[i]+r[n-i-1] for i in range(n)))
### BUGGY CODE ###

import numpy as np
from copy import deepcopy
n = int(input())
a = list(map(int, input().split()))
c = [0] * n
for i in range(n):
    c[i] = c[i - 1] + a[i]
c = np.array(c)
ans1, ans2 = 0, 0
tmp = deepcopy(c)
for i in range(n):
    t = tmp[i]
    if i % 2 == 0 and tmp[i] >= 0:
        tmp -= t + 1
        ans1 += t + 1
    elif i % 2 == 1 and tmp[i] <= 0:
        tmp += -t + 1
        ans1 += -t + 1
tmp = deepcopy(c)
for i in range(n):
    t = tmp[i]
    if i % 2 == 1 and tmp[i] >= 0:
        tmp -= t + 1
        ans2 += t + 1
    elif i % 2 == 0 and tmp[i] <= 0:
        tmp += -t + 1
        ans2 += -t + 1
print(min(ans1, ans2))

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
s = [a[0]]
for i in range(1, n):
    s.append(s[i-1]+a[i])
ans1, ans2 = 0, 0
for i in range(n):
    if s[i]*((-1)**i) <= 0:
        ans1 += abs(s[i]-(-1)**i)
        s[i] = (-1)**i
    if i+1 <= n-1:
        s[i+1] = s[i]+a[i+1]
s = [a[0]]
for i in range(1, n):
    s.append(s[i-1]+a[i])
for i in range(n):
    if s[i]*((-1)**(i+1)) <= 0:
        ans2 += abs(s[i]-(-1)**(i+1))
        s[i] = (-1)**(i+1)
    if i+1 <= n-1:
        s[i+1] = s[i]+a[i+1]
print(min(ans1, ans2))
### BUGGY CODE ###

n = int(input())
moto = [int(i) for i in input().split()]

array=[0]*n

for i in reversed(range(1,n+1)):
  sum = 0
  for j in range(i,n+1,i):
    sum += array[j-1]
  if array[i-1] != (sum-moto[i-1])%2:
    array[i-1] = 1

m = array.count(1)
ans = ""
for i in range(n):
  if array[i] == 1:
    ans = ans + str(i+1) + " "
print(m)
if ans != "":
  print(ans[:-1])



### FIXED CODE ###

n = int(input())
moto = [int(i) for i in input().split()]
 
array=[0]*n
 
for i in reversed(range(1,n+1)):
  if sum(array[i-1::i])%2 != moto[i-1]:
    array[i-1] = 1
    
m = sum(array)
print(m)
ans = ""
for i in range(n):
  if array[i] == 1:
    print(i+1, end=" ")
### BUGGY CODE ###

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

saikoro = [0] * 1001
for i in range(1, 1001):
    saikoro[i] = (saikoro[i-1] + i)


 
 
ans = 0
for j in range(n - k + 1):
    sums = 0
    for z in range(j,j + k):
        sums += saikoro[p[z]] / p[z]
    ans = max(ans, sums)
 
print(ans)

### FIXED CODE ###

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

saikoro = [0] * 1001
for i in range(1, 1001):
    saikoro[i] = (saikoro[i-1] + i)

s = [0] * (n + 1)
for u in range(1,n + 1):
    s[u] = saikoro[p[u - 1]] / p[u - 1] + s[u - 1]

ans = 0
for j in range(k - 1,n):
    ans = max(ans, s[j + 1] - s[j + 1 - k])
 
print(ans)
### BUGGY CODE ###

# from math import factorial,sqrt,ceil #,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from bisect import bisect_left
# from heapq import heappush,heappop
# from numba import njit
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from fractions import gcd

# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
import networkx as nx
G = nx.Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
MOD = 10**9 + 7
N,M = map(int,input().split())

G.add_nodes_from(list(range(1,N+1)))
for _ in range(M):
    A,B = map(int,input().split())
    G.add_edge(A, B)

shortestPath = nx.shortest_path(G, target=1)
ans = ["Yes"]
for i in range(2,N+1):
    if not i in shortestPath:
        print("No")
        exit()
    ans.append(shortestPath[i][1])

print(*ans,sep="\n")
# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))


### FIXED CODE ###

# from math import factorial,sqrt,ceil #,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from bisect import bisect_left
# from heapq import heappush,heappop
# from numba import njit,jit
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from fractions import gcd

# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
from networkx import Graph
from networkx.algorithms.traversal.breadth_first_search import bfs_predecessors
G = Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
N,M = map(int,input().split())
rows = [list(map(int,input().split())) for _ in range(M)]

G.add_edges_from(rows)

# shortestPath = shortest_path(G,target=1)
preds = bfs_predecessors(G,source=1)
# shortestPath = single_target_shortest_path(G,target=1)
# shortestPathLength,shortestPath = single_source_dijkstra(G,source=1)

preds = dict(preds)
if len(preds)+1 != N:
    print("No")
    exit()

print("Yes")
for i in range(2,N+1):
    print(preds[i])
### BUGGY CODE ###

k = int(input())
i = 0
s = 0

if k % 2 == 0:
    print('-1')
    exit()

while True:
    i += 1
    s = (7 + 10*s) % k
    if s == 0:
        break

print(i)

### FIXED CODE ###

K = int(input())
 
num = 0
cnt = 0
ans = -1
 
for i in range(K):
    num = num*10 +7
    cnt += 1
    if num%K != 0:
        num = num%K
    else:
        ans = cnt
        break
    
print(ans)
### BUGGY CODE ###

import sys

R, G, B, N = map(int, sys.stdin.readline().split())

r_max = N // R
g_max = N // G

ans = 0
for r in range(r_max+1):
    for g in range(g_max+1):
        res = N - r * R - g * G
        if 0 <= res and res % B == 0:
            # print(r, g, res // B)
            ans += 1

print(ans)

### FIXED CODE ###

import sys

R, G, B, N = map(int, sys.stdin.readline().split())

r_max = N // R
g_max = N // G

ans = 0
for r in range(r_max+1):
    for g in range(g_max+1):
        res = N - r * R - g * G
        if 0 <= res and res % B == 0:
            # print(r, g, res // B)
            ans += 1

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

N, K = map(int, input().split())
H = list(map(int, input().split()))
dp = [10**9+1] * N
dp[0] = 0

for n in range(N):
    for k in range(n+1, min(n+K+1, N)):
        dp[k] = min(dp[k], dp[n] + abs(H[k] - H[n]))

print(dp[N-1])


### FIXED CODE ###

N, K = map(int, input().split())
H = list(map(int, input().split()))
dp = [10**9+1] * N
dp[0] = 0

for n in range(N):
    for k in range(n+1, min(n+K+1, N)):
        dp[k] = min(dp[k], dp[n] + abs(H[k] - H[n]))

print(dp[N-1])
### BUGGY CODE ###

from collections import Counter

N = int(input())
C = tuple(map(lambda x: int(x)-1,input().split()))

adj = [list() for _ in range(N)]
for _ in range(N-1):
    a,b = map(int,input().split())
    adj[a-1].append(b-1)
    adj[b-1].append(a-1)


parent = [None]*N
parent[0] = -1

degree = [0]*N
stack = [0]
while stack:
    p = stack.pop()
    for c in adj[p]:
        if parent[c] is None:
            parent[c] = p
            degree[p] += 1
            stack.append(c)

leaves = [i for i in range(N) if degree[i] == 0]

dp = [Counter() for _ in range(N)] # color-wise counter
subtreesize = [0]*N
cnt = [0]*N

while leaves:
    c = leaves.pop()
    p = parent[c]


    if p >= 0:
        dp[c][C[c]] = subtreesize[c]+1
        x = subtreesize[c]-dp[c][C[p]]+1
        cnt[C[p]] += x*(x+1)//2
        subtreesize[p] += subtreesize[c]+1
        dp[p] += dp[c]
        dp[c] = None
        degree[p] -= 1
        if degree[p] == 0:
            leaves.append(p)

dp[0][C[0]] = subtreesize[0]+1
for c in range(N):
    x = subtreesize[0]-dp[0][c]+1
    cnt[c] += x*(x+1)//2

total = (subtreesize[0]+1)*(subtreesize[0]+2)//2

print(*(total-v for v in cnt), sep='\n')


### FIXED CODE ###

from collections import defaultdict
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

N = int(readline())
C = tuple(map(lambda x: int(x)-1, readline().split()))

temp = map(int,read().split())
temp = zip(temp,temp)

adj = [list() for _ in range(N)]
for a,b in temp:
    adj[a-1].append(b-1)
    adj[b-1].append(a-1)


parent = [None]*N
parent[0] = -1

stack = [0]
order = []
while stack:
    p = stack.pop()
    order.append(p)
    for c in adj[p]:
        if parent[c] is None:
            parent[c] = p
            stack.append(c)

def merge(a,b):
    if len(a) > len(b):
        a,b = b,a
    for k,v in a.items():
        b[k] += v
    return b

dp = [defaultdict(int) for _ in range(N)] # color-wise counter
subtreesize = [0]*N
cnt = [N*(N+1)//2]*N

for c in reversed(order):
    p = parent[c]
    if p >= 0:
        dp[c][C[c]] = subtreesize[c]+1
        x = subtreesize[c]-dp[c][C[p]]+1
        cnt[C[p]] -= x*(x+1)//2
        subtreesize[p] += subtreesize[c]+1

        dp[p] = merge(dp[c],dp[p])
        dp[c] = None

dp[0][C[0]] = subtreesize[0]+1
for c in range(N):
    x = subtreesize[0]-dp[0][c]+1
    cnt[c] -= x*(x+1)//2

print(*cnt, sep='\n')