CF600E Lomsat gelral

// Problem: CF600E Lomsat gelral
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF600E
// Memory Limit: 250 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

inline void out(ll x){
	if (x < 0) x = ~x + 1, putchar('-');
	if (x > 9) out(x / 10);
	putchar(x % 10 + '0');
}

inline void write(ll x){
	if (x < 0) x = ~x + 1, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
	puts("");
}

#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)
const int maxn=100000+100;

int n,col[maxn];
vector<int>g[maxn];
ll ans[maxn],sum;
int son[maxn],siz[maxn],cnt[maxn],maxx,Son;

void dfs1(int u,int fa){
	siz[u]=1;
	for(int i=0;i<g[u].size();i++){
		int j=g[u][i];
		if(j==fa) continue;
		dfs1(j,u);
		siz[u]+=siz[j];
		if(siz[j]>siz[son[u]]) son[u]=j;
	}
}

void add(int u,int fa,int val){
	cnt[col[u]]+=val;
	if(cnt[col[u]]>maxx) maxx=cnt[col[u]],sum=col[u];
	else if(cnt[col[u]]==maxx) sum+=col[u]*1ll;
	for(int i=0;i<g[u].size();i++){
		int j=g[u][i];
		if(j==fa||j==Son) continue;
		add(j,u,val);
	}
}

void dfs2(int u,int fa,int op){
	for(int i=0;i<g[u].size();i++){
		int j=g[u][i];
		if(j==fa) continue;
		if(j!=son[u]) dfs2(j,u,0);
	}
	if(son[u]) dfs2(son[u],u,1),Son=son[u];
	add(u,fa,1);Son=0;
	ans[u]=sum;
	if(!op) add(u,fa,-1),sum=0,maxx=0;
}

int main(){
	n=read;
	rep(i,1,n) col[i]=read;
	rep(i,1,n-1){
		int u=read,v=read;
		g[u].push_back(v);
		g[v].push_back(u);
	}	
	dfs1(1,0);
	dfs2(1,0,0);
	rep(i,1,n) printf("%lld ",ans[i]);
	
	
	return 0;
} 

原文地址:https://www.cnblogs.com/OvOq/p/15049585.html