2019.03.09 bzoj4999: This Problem Is Too Simple!(树链剖分+线段树动态开点)

时间:2021-05-17 14:37:42

传送门

题意:给一颗树,每个节点有个初始值,要求支持将i节点的值改为x或询问i节点到j节点的路径上有多少个值为x的节点。


思路:

考虑对每种颜色动态开点,然后用树剖+线段树维护就完了。

代码:

#include<bits/stdc++.h>
#define ri register int
using namespace std;
inline int read(){
    int ans=0;
    char ch=getchar();
    while(!isdigit(ch))ch=getchar();
    while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar();
    return ans;
}
const int N=1e5+5,M=2e5+5;
int n,m,id=0,tot=0,siz[N],num[N],col[N],rt[N+M],fa[N],dep[N],hson[N],top[N];
vector<int>e[N];
map<int,int>S;
void dfs1(int p){
    siz[p]=1;
    for(ri i=0,v;i<e[p].size();++i){
        if((v=e[p][i])==fa[p])continue;
        fa[v]=p,dep[v]=dep[p]+1,dfs1(v),siz[p]+=siz[v];
        if(siz[v]>siz[hson[p]])hson[p]=v;
    }
}
void dfs2(int p,int tp){
    top[p]=tp,num[p]=++tot;
    if(!hson[p])return;
    dfs2(hson[p],tp);
    for(ri i=0,v;i<e[p].size();++i)if((v=e[p][i])!=fa[p]&&v!=hson[p])dfs2(v,v);
}
namespace SGT{
    #define lc (son[p][0])
    #define rc (son[p][1])
    #define mid (l+r>>1)
    int siz[(N+M)*30],son[(N+M)*30][2],tot=0;
    inline void update(int&p,int l,int r,int k,int v){
        if(!p)p=++tot;
        siz[p]+=v;
        if(l==r)return;
        k<=mid?update(lc,l,mid,k,v):update(rc,mid+1,r,k,v);
    }
    inline int query(int p,int l,int r,int ql,int qr){
        if(!siz[p])return 0;
        if(ql<=l&&r<=qr)return siz[p];
        if(qr<=mid)return query(lc,l,mid,ql,qr);
        if(ql>mid)return query(rc,mid+1,r,ql,qr);
        return query(lc,l,mid,ql,mid)+query(rc,mid+1,r,mid+1,qr);
    }
    #undef lc
    #undef rc
    #undef mid
}
inline int query(int x,int y,int t){
    if(!t)return 0;
    int ret=0;
    while(top[x]^top[y]){
        if(dep[top[x]]<dep[top[y]])swap(x,y);
        ret+=SGT::query(rt[t],1,300000,num[top[x]],num[x]),x=fa[top[x]];
    }
    if(dep[x]<dep[y])swap(x,y);
    return ret+SGT::query(rt[t],1,300000,num[y],num[x]);
}
int main(){
    n=read(),m=read();
    for(ri i=1;i<=n;++i)if(!S[col[i]=read()])S[col[i]]=++id;
    for(ri i=1,u,v;i<n;++i)u=read(),v=read(),e[u].push_back(v),m,e[v].push_back(u);
    dfs1(1),dfs2(1,1);
    for(ri i=1;i<=n;++i)SGT::update(rt[S[col[i]]],1,300000,num[i],1);
    char s[2];
    for(ri x,y;m;--m){
        scanf("%s",s);
        if(s[0]=='Q')cout<<(x=read(),y=read(),query(x,y,S[read()]))<<'\n';
        else{
            x=read(),y=read();
            if(!S[y])S[y]=++id;
            SGT::update(rt[S[col[x]]],1,300000,num[x],-1);
            col[x]=y;
            SGT::update(rt[S[col[x]]],1,300000,num[x],1);
        }
    }
    return 0;
}