DSU ON TREE模板

以CF600E为例,其他的题大致框架都差不多这样

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>

using namespace std;
#define endl '\n'
#define int long long 
const int maxn = 1e5 + 5;
const int maxm = maxn << 1;
int a[maxn],n,son[maxn],ans[maxn],sz[maxn],num[maxn],now,skip,maxx;
int head[maxn],nex[maxm],v[maxm],w[maxm],cnt,dis[maxn],vis[maxn];
void add(int x,int y){
    nex[++cnt] = head[x];
    head[x] = cnt;
    v[cnt] = y;
}
void dfs1(int node,int fa){
    sz[node] = 1;
    for (int i = head[node]; i; i = nex[i]) {
        int to = v[i];
        if (to == fa) continue;
        dfs1(to,node);
        sz[node] += sz[to];
        if (!son[node] || sz[son[node]] < sz[to]) son[node] = to;
    }
}
void cal(int node,int fa,int val){//只需要修改计算子树贡献的函数就可以
    num[a[node]] += val;
    if (num[a[node]] == maxx) now += a[node];
    else if (num[a[node]] > maxx){
        maxx = num[a[node]];
        now = a[node];
    }
    for (int i = head[node]; i; i = nex[i]) {
        int to = v[i];
        if (to == fa || to == skip) continue;
        cal(to,node,val);
    }
}
void dfs(int node,int fa,bool clear){
    for (int i = head[node]; i; i = nex[i]) {
        int to = v[i];
        if (to == fa || to == son[node]) continue;
        dfs(to,node, true);
    }
    if (son[node]) dfs(son[node],node, false);
    skip = son[node];
    //下面这里也需要看情况修改
    cal(node,fa,1);
  
    skip = 0;
    ans[node] = now;
    if (clear){
        cal(node,fa,-1);
        now = maxx = 0;
    }
}
signed main(){
    std::ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
#ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    for (int i = 1; i <= n - 1; ++i) {
        int x,y;
        cin >> x >> y;
        add(x,y);
        add(y,x);
    }
    dfs1(1,0);
    dfs(1,0, false);
    for (int i = 1; i <= n; ++i) {
        cout << ans[i] << ' ';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值