# BZOJ[4999]This Problem Is Too Simple！ 树链剖分

#include<algorithm>
#include<ctype.h>
#include<cstdio>
#include<map>
#define N 100010
using namespace std;
int x=0,f=1;char c;
do c=getchar(),f=c=='-'?-1:f; while(!isdigit(c));
do x=(x<<3)+(x<<1)+c-'0',c=getchar(); while(isdigit(c));
return x*f;
}
map<int,int>b;
char c[5];
int n,m,x,y,k,Top,cnt,T;
int fir[N],a[N],dep[N],fa[N],siz[N],top[N],tree[N],pre[N],son[N];
struct Node{
Node *ls,*rs;
int sum;
Node():ls(NULL),rs(NULL),sum(0){}
inline void maintain(){
sum=0;
if(ls) sum+=ls->sum;
if(rs) sum+=rs->sum;
}
}*root[N<<2];
struct Edge{
int to,nex;
Edge(int _=0,int __=0):to(_),nex(__){}
}nex[N<<1];
nex[++Top]=Edge(y,fir[x]);
fir[x]=Top;
}
void dfs1(int x,int Fa,int Dep){
dep[x]=Dep;fa[x]=Fa;
siz[x]=1;
for(int i=fir[x];i;i=nex[i].nex){
if(nex[i].to==Fa) continue;
dfs1(nex[i].to,x,Dep+1);
siz[x]+=siz[nex[i].to];
if(siz[nex[i].to]>siz[son[x]]) son[x]=nex[i].to;
}
}
void dfs2(int x,int Top){
top[x]=Top;tree[x]=++T;pre[T]=x;
if(!son[x]) return;
dfs2(son[x],Top);
for(int i=fir[x];i;i=nex[i].nex){
if(nex[i].to==fa[x] || nex[i].to==son[x]) continue;
dfs2(nex[i].to,nex[i].to);
}
}
void Change(int L,int R,int x,int v,Node *&k){
if(!k) k=new Node;
if(L==R){
k->sum=v;
return;
}
int mid=(L+R)>>1;
if(x<=mid) Change(L,mid,x,v,k->ls);
else Change(mid+1,R,x,v,k->rs);
k->maintain();
return;
}
int Query(int L,int R,int x,int y,Node *k){
if(!k) return 0;
if(L>=x && R<=y){
return k->sum;
}
int mid=(L+R)>>1;
if(y<=mid) return Query(L,mid,x,y,k->ls);
else if(x>mid) return Query(mid+1,R,x,y,k->rs);
else return Query(L,mid,x,y,k->ls)+Query(mid+1,R,x,y,k->rs);
}
inline int Query_Tree(int x,int y,int k){
int tmp=0;
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]])
swap(x,y);
tmp=tmp+Query(1,N,tree[top[x]],tree[x],root[k]);
x=fa[top[x]];
}
if(tree[x]>tree[y]) swap(x,y);
tmp=tmp+Query(1,N,tree[x],tree[y],root[k]);
return tmp;
}
int main(){
for(int i=1;i<=n;i++){
if(!b[a[i]]) b[a[i]]=++cnt;
}
for(int i=1;i<n;i++){
}
dfs1(1,1,0);dfs2(1,1);
for(int i=1;i<=n;i++)
Change(1,N,tree[i],1,root[b[a[i]]]);
for(int i=1;i<=m;i++){
scanf("%s",c+1);
if(c[1]=='Q'){
if(!b[k]) printf("0\n");
else printf("%d\n",Query_Tree(x,y,b[k]));
}
else{
Change(1,N,tree[x],0,root[b[a[x]]]);
if(!b[y]) b[y]=++cnt;
Change(1,N,tree[x],1,root[b[a[x]=y]]);
}
}
return 0;
}


©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客