PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000097. Những màu xuất hiện nhiều nhất (Lomsat gelral)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Những màu xuất hiện nhiều nhất (Lomsat gelral)

Lomsat gelral

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a tree with nn vertices numbered from 11 to nn, rooted at vertex 11. Vertex ii has positive integer color cic_i.

The subtree of vv contains vertex vv and all its descendants. Let freqv(c)\mathrm{freq}_v(c) be the number of vertices of color cc in this subtree.

A color is called dominating in the subtree if its frequency is maximal among all colors present there. Several colors may be tied for the maximum.

For every vertex vv, output the sum of the numeric color IDs of all dominating colors in its subtree. Count each dominating color ID exactly once, regardless of how many vertices have that color.

Input

The first line contains nn. The second line contains nn color IDs c1,c2,…,cnc_1,c_2,\ldots,c_n. Each of the next n−1n-1 lines contains two vertices u,vu,v representing an edge.

Output

Print nn integers; the vv-th is the sum of dominating color IDs in the subtree rooted at vv.

Subtasks

  • Subtask 1 (10 points): n≤40n\le 40.
  • Subtask 2 (20 points): n≤1500n\le 1500.
  • Subtask 3 (30 points): n≤15000n\le 15000.
  • Subtask 4 (40 points): n≤100000n\le 100000.

Conditions shared by all subtasks: For every group: 1≤n≤1000001\le n\le100000, 1≤ci≤n1\le c_i\le n, 1≤u,v≤n1\le u,v\le n. The edges form an undirected tree rooted at 11.

Examples

Example 1

Input

4
1 2 3 4
1 2
2 3
2 4

Output

10 9 3 4

Explanation

For vertex 11, colors 1,2,3,41,2,3,4 each occur once, so all four dominate and the sum is 1010. Vertex 22 has subtree colors 2,3,42,3,4, summing to 99. Each leaf's subtree has just its own color, giving 33 and 44.

Example 2

Input

15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13

Output

6 5 4 3 2 3 3 1 1 3 2 2 1 2 3

Explanation

In example 2, colors 1,2,31,2,3 each occur five times in the entire tree, so their sum is 66 for the root. At vertex 22, colors 22 and 33 tie for the highest frequency, producing 55.