BZOJ P1103 「POI2007」大都市meg【dfs序】【樹狀陣列+差分】
阿新 • • 發佈:2018-12-13
#include <queue> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define ll long long #define rep(i,x,y) for(ll i=(x);i<=(y);i++) #define repd(i,x,y) for(ll i=(x);i>=(y);i--) using namespace std; const ll N=3e5+5; ll bit[N]; ll n,m,tim,in[N],out[N],deep[N]; ll cnt,to[N<<1],nxt[N<<1],head[N]; #define lowbit(x) (x&(-x)) inline ll read() { ll x=0;char ch=getchar();bool f=0; while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();} return f?-x:x; } void ins(ll x,ll y) { to[++cnt]=y;nxt[cnt]=head[x];head[x]=cnt; } void dfs(ll x,ll fa) { in[x]=++tim; deep[x]=deep[fa]+1; for(int i=head[x];i;i=nxt[i]) if(to[i]!=fa) dfs(to[i],x); out[x]=tim; } void update(ll x,ll y) { for(;x<=n;x+=lowbit(x)) bit[x]+=y; } ll getsum(ll x) { ll ret=0;for(;x;x-=lowbit(x)) ret+=bit[x];return ret; } int main() { n=read(); rep(i,1,n-1) { ll x=read(),y=read(); ins(x,y),ins(y,x); } dfs(1,0); m=read(); rep(i,1,n+m-1) { char ch[2]; scanf("%s",ch+1); if(ch[1]=='W') { ll x=read(); printf("%lld\n",deep[x]-1-getsum(in[x])); } else { ll x=read(),y=read(); if(deep[x]<deep[y]) swap(x,y); update(in[x],1),update(out[x]+1,-1); } } return 0; }