Codeforces 620E New Year Tree

http://codeforces.com/problemset/problem/620/E

题意:
给以一棵树,每个结点刚开始的时候都有一个颜色,现在有查询1 u col:给这个结点及其子树染上col这种颜色,2 u:查询以u为根节点的子树的所有颜色种类

分析:
显然是到线段树的题目,要把每个节点的子树放到一个区间上,并且记录首尾位置,这样就可以更新颜色的时候成段更新,查询颜色种类的时候区间查询。所以用dfs遍历整棵树,fir数组记录根节点位置,la数组保存子树的最后一个位置,用个数组当做哈希索引ha,保存线段树每个点对应的树上的某个节点,然后就是基本的线段树操作了。
PS:
对于颜色的保存,因为只有60种颜色,用二进制就好了,如果更多的话可以用字符串,也可以用数组。
代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N=4e5+5;
vector<int>e[N];
int fir[N],la[N],a[N],ha[N];
bool vis[N];
int id;
void dfs(int u)
{
    fir[u]=id; ha[id]=u; vis[u]=1;
    for(int i=0;i<e[u].size();i++){
        if(!vis[e[u][i]]){
            ++id;dfs(e[u][i]);
        }
    }
    la[u]=id;
}
ll sum[N<<2]; //保存所有节点的颜色
int col[N<<2]; //标记子树涂上什么颜色
void pushup(int rt)
{
    sum[rt]=sum[rt<<1]|sum[rt<<1|1];
}
void pushdown(int rt)
{
    if(col[rt]){
        col[rt<<1]=col[rt<<1|1]=col[rt];
        sum[rt<<1]=sum[rt<<1|1]=1ll<<col[rt];
        col[rt]=0;
    }
}
void build(int l,int r,int rt)
{
    if(l==r){
        sum[rt]=1ll<<(a[ha[l]]);
        col[rt]=0;return;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushup(rt);
}
void update(int a,int b,int c,int l,int r,int rt)
{
    if(a<=l&&r<=b){
        sum[rt]=1ll<<c;
        col[rt]=c;
        return;
    }
    int m=(l+r)>>1;
    pushdown(rt);
    if(a<=m)update(a,b,c,lson);
    if(b>m)update(a,b,c,rson);
    pushup(rt);
}
ll query(int a,int b,int l,int r,int rt)
{
    if(a<=l&&r<=b){
        return sum[rt];
    }
    int m=(l+r)>>1;
    pushdown(rt);
    ll ans=0;
    if(a<=m)ans|=query(a,b,lson);
    if(b>m)ans|=query(a,b,rson);
    return ans;
}
int main()
{
    int n,m,u,v;
    //freopen("f.txt","r",stdin);
    scanf("%d%d",&n,&m);
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    for(int i=1;i<n;i++){
        scanf("%d%d",&u,&v);
        e[u].push_back(v);e[v].push_back(u);
    }
    id=1;
    dfs(1);
    build(1,n,1);
    while(m--){
        int op,col;
        scanf("%d",&op);
        if(op==1){
            scanf("%d%d",&u,&col);
            update(fir[u],la[u],col,1,n,1);
        }
        else{
            scanf("%d",&u);
            ll ans=query(fir[u],la[u],1,n,1);
            int tot=0;
            while(ans){
                if(ans&1)tot++;
                ans>>=1;
            }
            printf("%d\n",tot);
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值