Lomsat gelral
Time limit 2 seconds
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.
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
题意:给出一棵树和每个点的颜色,问每个子树中出现最多的颜色的和是多少.
思路:DSU on tree,先更新轻儿子最后重儿子,轻儿子更新完就暴力clear掉,重儿子不用clear,如果当前点是父亲的轻儿子,更新完以当前点为根的子树后随即暴力清理掉所有标记,更新时暴力把所有轻儿子都重新计算. 可证明每个点最多被暴力log次.
复杂度:nlogn.
HDU-6430也是dsu好题.
代码:
#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const ll mod = 998244353;
const int maxn = 2e5+5;
struct edge
{
int u,v,ne;
} e[maxn];
int n;
ll c[maxn],ans[maxn],num[maxn],maxc,sum;
int head[maxn],len;
int ve[maxn],son[maxn],vis[maxn];
void add(int u,int v)
{
e[len].u = u;
e[len].v = v;
e[len].ne = head[u];
head[u] = len++;
}
void dfs1(int x,int p)
{
ve[x] = 1;
son[x] = -1;
for(int i = head[x];i!= -1;i = e[i].ne)
{
int v = e[i].v;
if(v == p) continue;
dfs1(v,x);
ve[x]+= ve[v];
if(son[x] == -1||ve[v]> ve[son[x]])
son[x] = v;
}
return ;
}
void update(int x,int p)
{
num[c[x]]++;
if(num[c[x]]> maxc)
{
sum = c[x];
maxc = num[c[x]];
}
else if(num[c[x]] == maxc) sum+= c[x];
for(int i = head[x];i!= -1;i = e[i].ne)
{
if(e[i].v == p||vis[e[i].v]) continue;//更新时跳过重儿子
update(e[i].v,x);
}
return ;
}
void clear(int x,int p)
{
num[c[x]] = 0;
for(int i = head[x];i!= -1;i = e[i].ne)
{
if(e[i].v == p) continue;
clear(e[i].v,x);
}
return ;
}
void dfs2(int x,int p,int sta)
{
for(int i = head[x];i!= -1;i = e[i].ne)
{
int v = e[i].v;
if(v == son[x]||v == p) continue;
dfs2(v,x,0);
}
if(son[x]!= -1) dfs2(son[x],x,1),vis[son[x]] = 1;//把重儿子标记
update(x,p);
if(son[x]!= -1) vis[son[x]] = 0;//记得归零
ans[x] = sum;
if(sta == 0)//当前点是轻儿子的话就clear掉
{
sum = 0;
maxc = 0;
clear(x,p);
}
return ;
}
int main()
{
mem(head,-1);
cin>>n;
for(int i = 1;i<= n;i++)
scanf("%lld",&c[i]);
for(int i = 1,x,y;i< n;i++)
{
scanf("%d %d",&x,&y);
add(x,y);
add(y,x);
}
dfs1(1,-1);
dfs2(1,-1,1);
for(int i = 1;i<= n;i++)
printf("%lld ",ans[i]);
return 0;
}