CF600E Lomsat gelral (启发式合并)

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
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
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

题解:题意就是定义一个节点的优势点为他的子树中出现次数最多的数字,(可能会有多个优势点),让你求每一个点的优势点的和;
可以用map记录每一个点的各个优势点,记录每点的子树中每个数字出现的次数,然后dfs。
参考代码:
 #include<bits/stdc++.h>
using namespace std;
#define clr(a,val) memset(a,val,sizeof(a))
#define pb push_back
#define fi first
#define se second
typedef long long ll;
const int maxn=1e5+;
int n,cnt;
int col[maxn],head[maxn],dy[maxn];
ll ans[maxn];
struct Edge{
int to,nxt;
} edge[maxn<<];
map<int,int> mp[maxn];
map<int,ll> sum[maxn];
map<int,int>::iterator it1,it2;
inline int read()
{
int x=,f=;char ch=getchar();
while(ch<'' || ch>''){if(ch=='-') f=-;ch=getchar();}
while(ch>='' && ch<=''){x=(x<<)+(x<<)+ch-'';ch=getchar();}
return x*f;
} inline void addedge(int u,int v)
{
edge[cnt].to=v;
edge[cnt].nxt=head[u];
head[u]=cnt++;
} inline void dfs(int u,int fa)
{
for(int e=head[u];~e;e=edge[e].nxt)
{
int v=edge[e].to;
if(v==fa) continue;
dfs(v,u);
if(mp[dy[u]].size()<mp[dy[v]].size()) swap(dy[u],dy[v]);
for(it1=mp[dy[v]].begin();it1!=mp[dy[v]].end();it1++)
{
sum[dy[u]][mp[dy[u]][(*it1).fi]]-=(*it1).fi;
mp[dy[u]][(*it1).fi]+=(*it1).se;
sum[dy[u]][mp[dy[u]][(*it1).fi]]+=(*it1).fi;
}
}
ans[u]=(*sum[dy[u]].rbegin()).se;
} int main()
{
n=read();
for(int i=;i<=n;++i) col[i]=read(),dy[i]=i,mp[i][col[i]]=,sum[i][]=col[i];
int u,v;cnt=;clr(head,-);
for(int i=;i<n;++i)
{
u=read();v=read();
addedge(u,v);addedge(v,u);
}
dfs(,);
for(int i=;i<=n;++i) printf("%lld%c",ans[i],i==n? '\n':' '); return ;
}
上一篇:Educational Codeforces Round 64 部分题解


下一篇:QTP的那些事--项目实践操作案例代码--查询操作