P4271 解题报告
前言
『究极折磨篇』LCT 题单里的,顺便宣传下『从入门到入土』树链剖分学习笔记。
思路分析
因为题目中有动态加边操作,形态也是森林,所以直接考虑使用 LCT。
是否在同一颗树中考虑使用并查集解决,那么剩下的问题就是如何求这颗树中离
考虑离他最远的点肯定是树的直径的两个端点之一,题意就变成了 LCT 维护直径。
那么新加一个点的时候,考虑加上原本直径的两个点,一共三个点,两两求个距离取最大即可。
代码
#include <bits/stdc++.h>
#define ls son[x][0]
#define rs son[x][1]
#define int long long
using namespace std;
const int N=1e5+10,mod=1e9+7,INF=0x3f3f3f3f3f3f3f3f;
struct node
{int x,y,w;}d[N];
int n,m;
int f[N],s[N],son[N][2],st[N],r[N],fa[N];
static char buf[1000000],*paa=buf,*pd=buf;
//#define getchar() paa==pd&&(pd=(paa=buf)+fread(buf,1,1000000,stdin),paa==pd)?EOF:*paa++
inline int read(void){
int x(0),t(1);char fc(getchar());
while(!isdigit(fc)){if(fc=='-') t=-1;fc=getchar();}
while(isdigit(fc)) x=(x<<1)+(x<<3)+(fc^48),fc=getchar();
return x*t;
}
inline void print(int x)
{
if(x<0) putchar('-'),x=-x;
if(x>9) print(x/10);
putchar(x%10+'0');
}
inline bool ntrt(int x){return son[f[x]][1]==x||son[f[x]][0]==x;}
inline void pushup(int x){s[x]=s[ls]+s[rs]+1;}
inline void pushson(int x){swap(ls,rs),r[x]^=1;}
inline void pushdown(int x)
{
if(r[x])
{
if(ls) pushson(ls);
if(rs) pushson(rs);
r[x]=0;
}
}
inline void rotate(int x)
{
int y=f[x],z=f[y],k=(son[y][1]==x),w=son[x][!k];
if(ntrt(y)) son[z][son[z][1]==y]=x;son[x][!k]=y;son[y][k]=w;
if(w) f[w]=y;f[y]=x;f[x]=z;
pushup(y);
}
inline void Splay(int x)
{
int y=x,tot=0;st[++tot]=y;
while(ntrt(y)) st[++tot]=y=f[y];
while(tot) pushdown(st[tot--]);
while(ntrt(x))
{
y=f[x];int z=f[y];
if(ntrt(y)) rotate((son[y][0]==x)^(son[z][0]==y)?x:y);
rotate(x);
}
pushup(x);
}
inline int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
inline void access(int x){for(int y=0;x;x=f[y=x]) Splay(x),rs=y,pushup(x);}
inline void makert(int x){access(x);Splay(x);pushson(x);}
inline int findrt(int x)
{
access(x);Splay(x);
while(ls) pushdown(x),x=ls;
Splay(x);return x;
}
inline void split(int x,int y){makert(x);access(y);Splay(y);}
inline void link(int x,int y){makert(x);if(findrt(y)!=x)f[x]=y;}
inline int query(int x,int y){split(x,y);return s[y]-1;}
signed main()
{
m=read();
for(int i=1,x;i<=m;i++)
{
char op=getchar();while(op!='B'&&op!='Q') op=getchar();x=read();fa[i]=i;
if(op=='B')
{
n++;d[n].x=n,d[n].y=n;
if(~x)
{
link(n,x);x=find(x);fa[n]=x;
int a=n,b=d[x].x,c=d[x].y,mx=d[x].w,t=query(a,b);
if(t>mx) mx=t,d[x].x=a,d[x].y=b;t=query(a,c);
if(t>mx) mx=t,d[x].x=a,d[x].y=c;t=query(b,c);
if(t>mx) mx=t,d[x].x=b,d[x].y=c;d[x].w=mx;
}
}
else print(max(query(x,d[find(x)].x),query(x,d[find(x)].y))),puts("");
}
return 0;
}