E. Lomsat gelral
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
input
Copy
4 1 2 3 4 1 2 2 3 2 4
output
Copy
10 9 3 4
input
Copy
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
Copy
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
题目大意:
有一棵以1为根的树,每个节点都有颜色,颜色由数字表示,求以每个节点为根的子树占领子树的颜色和,即子树中最多的颜色的数字表示相加(可能有多种最多颜色)
(我觉得再怎么写博客也挽救不了我的语言表达能力了…
启发式合并真是个玄妙的东西。
思路:
首先考虑下每个节点需要记录,并合并给父节点的东西。对于每个节点记录,每个颜色及其个数统计cnt,每个个数所包括的是该个数的颜色数字和sum。从根节点1dfs遍历,先计算出子树的答案,再合并至父亲,合并时依据小的合并到大的的原则,判断每个子节点子树所包含的颜色个数,根据这个判断大小,父亲比儿子小的话就swap一下继续记录,得到的最终结果仍是父亲的。
特别要注意,应该建立双向边,因为题目中给边的时候并没有告诉我们哪个是父亲哪个是儿子;
并且建立双向边时,前向星写法的to与nxt数组的大小要<<1!要<<1!要<<1!
上代码:
#include
#include
#include
#include