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.
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.
Print n integers — the sums of dominating colours for each vertex.
4 1 2 3 4 1 2 2 3 2 4
10 9 3 4
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
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
分析:题意很简单,我理解的启发式合并,就是现在要把n堆元素合并成一个,每次可以合并两个,费用为合并的这两堆元素中任意一堆的大小,那么我们每次合并都可以贪心的选择将小的并入大的中,然后不难证明这样合并费用最多是n*logn*单位合并费用(最坏情况貌似是像完全二叉树那样合并?最好的情况应该是每次加一个单位进来,n*合并费用),这道题的话就是n*logn^2.
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<set>
#include<map>
#include<vector>
#include<cstring>
#include<stack>
#include<queue>
#define INF 0x3f3f3f3f
#define eps 1e-9
#define N 100005
#define MOD 998244353
using namespace std;
typedef long long ll;
int n,u,v,c[N],Max1[N],sum[N];
ll Max2[N],ans[N];
vector<int> G[N];
map<int,int> f[N];
void dfs(int u,int fa)
{
f[u][c[u]]++;
Max1[u] = 1;
Max2[u] = c[u];
for(int v : G[u])
if(v != fa)
{
dfs(v,u);
if(f[u].size() < f[v].size())
{
swap(f[u],f[v]);
swap(Max1[u],Max1[v]);
swap(Max2[u],Max2[v]);
}
for(auto it = f[v].begin();it != f[v].end();it++)
{
int who = it->first;
f[u][who] += it->second;
if(Max1[u] == f[u][who]) Max2[u] += who;
if(Max1[u] < f[u][who])
{
Max1[u] = f[u][who];
Max2[u] = who;
}
}
f[v].clear();
}
ans[u] = Max2[u];
}
int main()
{
scanf("%d",&n);
for(int i = 1;i <= n;i++) scanf("%d",&c[i]);
for(int i = 1;i < n;i++)
{
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1,-1);
for(int i = 1;i <= n;i++) printf("%I64d ",ans[i]);
}