题解:P15952 [ICPC 2018 Jakarta R] Rotating Gears
LastKismet · · 题解
显然考虑以深度最浅的点为一个连通块的特征。考虑描述
考虑一次操作,先找到操作点所在连通块,你树剖对每条重链用 set 维护被删点集,那么容易一个
然后有一个巧妙的实现,你对线段树上每个区间维护区间
实现上,你并不关心区间
const int N=1e5+5;
int n,q;
vec<int> g[N];
int sz[N],son[N],dfn[N],dcnt,nfd[N],dp[N],fa[N],tp[N];
void dfs0(int x){
sz[x]=1,dp[x]=dp[fa[x]]+1;
for(auto y:g[x])if(y!=fa[x])fa[y]=x,dfs0(y),sz[x]+=sz[y],sz[y]>sz[son[x]]&&(son[x]=y);
}
void dfs1(int x,int top){
dfn[x]=++dcnt,nfd[dcnt]=x,tp[x]=top;
if(son[x])dfs1(son[x],top);
for(auto y:g[x])if(y!=fa[x]&&y!=son[x])dfs1(y,y);
}
set<int> st[N];
int get(int x){
int res=x;
while(x){
if(st[tp[x]].empty()||*st[tp[x]].begin()>dfn[x])res=tp[x],x=fa[tp[x]];
else{auto z=*--st[tp[x]].upper_bound(dfn[x]);if(z!=dfn[x])res=nfd[z+1];break;}
}
return res;
}
namespace s0{
int cnt[N<<2],sz[N<<2],lac[N<<2];
ll dat[N<<2],lav[N<<2];
void build(int x=1,int l=1,int r=n){
if(l==r)return sz[x]=1,void();
int m=l+r>>1;
build(x<<1,l,m),build(x<<1|1,m+1,r);
sz[x]=sz[x<<1]+sz[x<<1|1];
}
il void push(int x){
cnt[x<<1]+=lac[x],cnt[x<<1|1]+=lac[x];
lac[x<<1]+=lac[x],lac[x<<1|1]+=lac[x];
lac[x]=0;
if(cnt[x<<1]==cnt[x])dat[x<<1]+=lav[x],lav[x<<1]+=lav[x];
if(cnt[x<<1|1]==cnt[x])dat[x<<1|1]+=lav[x],lav[x<<1|1]+=lav[x];
lav[x]=0;
}
il void update(int x){
sz[x]=dat[x]=0;
if(cnt[x<<1]==cnt[x])sz[x]+=sz[x<<1],dat[x]+=dat[x<<1];
if(cnt[x<<1|1]==cnt[x])sz[x]+=sz[x<<1|1],dat[x]+=dat[x<<1|1];
}
void modc(int lq,int rq,int v,int x=1,int l=1,int r=n){
if(lq<=l&&r<=rq)return cnt[x]+=v,lac[x]+=v,void();
int m=l+r>>1;push(x);
if(lq<=m)modc(lq,rq,v,x<<1,l,m);
if(m<rq)modc(lq,rq,v,x<<1|1,m+1,r);
update(x);
}
void modv(int lq,int rq,int c,int v,int x=1,int l=1,int r=n){
if(lq<=l&&r<=rq)return cnt[x]==c&&(dat[x]+=v,lav[x]+=v),void();
int m=l+r>>1;push(x);
if(lq<=m)modv(lq,rq,c,v,x<<1,l,m);
if(m<rq)modv(lq,rq,c,v,x<<1|1,m+1,r);
update(x);
}
int gcnt(int k,int x=1,int l=1,int r=n){
if(l==r)return cnt[x];
int m=l+r>>1;push(x);
return k<=m?gcnt(k,x<<1,l,m):gcnt(k,x<<1|1,m+1,r);
}
ll gdat(int k,int x=1,int l=1,int r=n){
if(l==r)return dat[x];
int m=l+r>>1;push(x);
return k<=m?gdat(k,x<<1,l,m):gdat(k,x<<1|1,m+1,r);
}
int gsiz(int lq,int rq,int c,int x=1,int l=1,int r=n){
if(lq<=l&&r<=rq)return cnt[x]==c?sz[x]:0;
int m=l+r>>1;push(x);int res=0;
if(lq<=m)res+=gsiz(lq,rq,c,x<<1,l,m);
if(m<rq)res+=gsiz(lq,rq,c,x<<1|1,m+1,r);
return res;
}
}
void INIT(){}
void MAIN(){
read(n);
rep(i,2,n){int x,y;read(x,y);g[x].pub(y),g[y].pub(x);}
dfs0(1),dfs1(1,1);
s0::build();
read(q);
rep(i,1,q){
int op,x;read(op,x);
if(op==1)st[tp[x]].insert(dfn[x]),s0::modc(dfn[x],dfn[x]+sz[x]-1,1);
else if(op==2)st[tp[x]].erase(dfn[x]),s0::modc(dfn[x],dfn[x]+sz[x]-1,-1);
else{
int v;read(v);
if(dp[x]&1)v=-v;
x=get(x);int c=s0::gcnt(dfn[x]);
s0::modv(dfn[x],dfn[x]+sz[x]-1,c,v);
put(abs(v)*s0::gsiz(dfn[x],dfn[x]+sz[x]-1,c));
}
}
ll ans=0;
rep(i,1,n){
ll v=s0::gdat(dfn[i]);
if(dp[i]&1)v=-v;
v%=360,v+=360,v%=360;
ans+=v;
}
put(ans);
}