#include<bits/stdc++.h>
#define maxn 100005
#define lc u<<1
#define rc u<<1|1
using namespace std;
int n,m;
int info[maxn],Prev[maxn<<1],to[maxn<<1],cnt_e;
void Node(int u,int v){ Prev[++cnt_e]=info[u],info[u]=cnt_e,to[cnt_e]=v; }
int son[maxn],tp[maxn],dep[maxn],mx[maxn<<2],ad[maxn<<2],ft[maxn],sz[maxn];
int st[maxn],ed[maxn],pos[maxn],tim;
int fa[maxn],ch[maxn][2];
void dfs1(int u,int ff){
pos[st[u] = ++tim] = u;
dep[u] = dep[fa[u] = ft[u] = ff] + 1;
sz[u] = 1;
for(int i=info[u],v;i;i=Prev[i]) if((v=to[i])^ff)
dfs1(v,u),sz[u]+=sz[v],(sz[v]>sz[son[u]]) && (son[u]=v);
ed[u] = tim;
}
void dfs2(int u,int ff){
if(son[u]) tp[son[u]]=tp[u],dfs2(son[u],u);
for(int i=info[u],v;i;i=Prev[i]) if((v=to[i])^ff && v^son[u])
dfs2(tp[v]=v,u);
}
void Build(int u,int l,int r){
if(l==r) return (void)(mx[u]=dep[pos[l]]);
int m=l+r>>1;
Build(lc,l,m),Build(rc,m+1,r);
mx[u] = max(mx[lc] , mx[rc]);
}
void dtp(int u,int v){ ad[u] += v,mx[u] += v; }
void dt(int u){ if(ad[u]) dtp(lc,ad[u]),dtp(rc,ad[u]),ad[u]=0; }
void add(int u,int l,int r,int ql,int qr,int v){
if(l>qr||ql>r) return;
if(ql<=l&&r<=qr) return (void)(dtp(u,v));
int m=l+r>>1;dt(u);
add(lc,l,m,ql,qr,v),add(rc,m+1,r,ql,qr,v);
mx[u] = max(mx[lc] , mx[rc]);
}
int qry(int u,int l,int r,int ql,int qr){
if(l>qr||ql>r) return 0;
if(ql<=l&&r<=qr) return mx[u];
int m=l+r>>1;dt(u);
return max(qry(lc,l,m,ql,qr),qry(rc,m+1,r,ql,qr));
}
#define pa fa[x]
int isr(int x){ return ch[pa][0]^x && ch[pa][1]^x; }
int inr(int x){ return ch[pa][1] == x; }
void rot(int x){
int y=fa[x],z=fa[y],c=inr(x);
if(!isr(y)) ch[z][inr(y)] = x;
(ch[y][c] = ch[x][!c]) && (fa[ch[y][c]] = y);
fa[fa[ch[x][!c]=y]=x]=z;
}
void splay(int x){
for(;!isr(x);rot(x))
if(!isr(pa))
rot(inr(x) ^ inr(pa) ? x : pa);
}
int sert(int x){ for(;ch[x][0];x=ch[x][0]);return x; }
int access(int x){
int y=0;
for(int p;x;x=fa[y=x]){
splay(x);
if(p=sert(ch[x][1])) add(1,1,n,st[p],ed[p],1);
if(p=sert(y)) add(1,1,n,st[p],ed[p],-1);
ch[x][1] = y;
}
return y;
}
int Lca(int u,int v){ for(;tp[u]^tp[v];u=ft[tp[u]])
if(dep[tp[u]] < dep[tp[v]]) swap(u,v);return dep[u] < dep[v] ? u : v; }
int main(){
scanf("%d%d",&n,&m);
for(int i=1,u,v;i<n;i++){
scanf("%d%d",&u,&v);
Node(u,v),Node(v,u);
}
dfs1(1,0),dfs2(tp[1]=1,0);
Build(1,1,n);
for(int op,x,y,t;m--;){
scanf("%d%d",&op,&x);
if(op == 1) access(x);
if(op == 2) scanf("%d",&y),t=Lca(x,y),printf("%d\n",qry(1,1,n,st[x],st[x])+qry(1,1,n,st[y],st[y])-2*qry(1,1,n,st[t],st[t])+1);
if(op == 3) printf("%d\n",qry(1,1,n,st[x],ed[x]));
}
}
SDOI2017 树点涂色(LCT维护到根颜色段)
最新推荐文章于 2021-12-31 10:27:53 发布