CF600E Lomsat gelral【题解】线段树合并

Luogu题目:https://www.luogu.com.cn/problem/CF600E

值域线段树加合并。

基本上就是裸的。

代码如下:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=1e5+10;
int c[maxn],n,cnt;
struct node{
    int nxt,to;
    #define nxt(x) e[x].nxt
    #define to(x) e[x].to
}e[maxn<<1];
int head[maxn],tot,rt[maxn],ans[maxn];
inline void add(int from,int to){
    to(++tot)=to;
    nxt(tot)=head[from];head[from]=tot;
}
struct tree{
    int lc,rc,tg,dt;
}t[maxn*50];
inline void pushup(int p){
    t[p].dt=max(t[t[p].lc].dt,t[t[p].rc].dt);
    if(t[t[p].lc].dt==t[t[p].rc].dt) t[p].tg=t[t[p].lc].tg+t[t[p].rc].tg;
    else t[p].tg= t[t[p].lc].dt > t[t[p].rc].dt ? t[t[p].lc].tg : t[t[p].rc].tg;
}
inline int merge(int p,int q,int l,int r){
    if(!p) return q;
    if(!q) return p;
    if(l==r){
        t[p].dt+=t[q].dt;
        t[p].tg=l;
        return p;
    }
    int mid=(l+r)>>1;
    t[p].lc=merge(t[p].lc,t[q].lc,l,mid);
    t[p].rc=merge(t[p].rc,t[q].rc,mid+1,r);
    pushup(p);
    return p;
}
void change(int &p,int l,int r,int wh){
    if(!p) p=++cnt;
    if(l==r){
        t[p].dt+=1;t[p].tg=wh;return;
    }
    int mid=(l+r)>>1;
    if(wh<=mid) change(t[p].lc,l,mid,wh);
    else change(t[p].rc,mid+1,r,wh);
    pushup(p);
}
int dfs(int now,int fa){
    for(int i=head[now];i;i=nxt(i)){
        int to=to(i);
        if(to==fa) continue;
        dfs(to,now);
        rt[now]=merge(rt[now],rt[to],1,maxn);
    }
    change(rt[now],1,maxn,c[now]);
    ans[now]=t[rt[now]].tg;
}
signed main()
{
    scanf("%lld",&n);
    for(int i=1;i<=n;i++)
        scanf("%lld",&c[i]),rt[i]=++cnt;
    for(int i=1;i<n;i++){
        int x,y;scanf("%lld%lld",&x,&y);
        add(x,y);add(y,x);
    }
    dfs(1,0);
    for(int i=1;i<=n;i++)
        printf("%lld ",ans[i]);
    return 0;
}

 

转载于:https://www.cnblogs.com/ChrisKKK/p/11544632.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值