题目的意思是让我们动态维护直径。
很容易得到以下两个定理:
1.两棵树合并以后的直径端点是原来两棵树的四个直径端点中的两个;
2.距离一个点最远的点一定是一个直径的端点。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
template<typename T>inline void qr(T &x){
x=0;int f=0;char s=getchar();
while(s<'0'||'9'<s)f|=s=='-',s=getchar();
while('0'<=s&&s<='9')x=x*10+s-48,s=getchar();
x=f?-x:x;
}
const int mxn=1e5+10;
int n,q,sta[mxn];bool rv[mxn];
int fa[mxn],ch[mxn][2],c[mxn],dx[mxn],dy[mxn];
#define lc ch[x][0]
#define rc ch[x][1]
#define ls(x) ch[x][0]
#define rs(x) ch[x][1]
bool nrt(int x){return ls(fa[x])==x||rs(fa[x])==x;}
void crv(int x){
if(!x)return;
swap(lc,rc);rv[x]^=1;
}
void pushdown(int x){
if(rv[x])
crv(lc),crv(rc),rv[x]=0;
dx[lc]=dx[rc]=dx[x];
dy[lc]=dy[rc]=dy[x];
}
void update(int x){
c[x]=c[lc]+c[rc]+1;
}
void rotate(int x){
int y=fa[x],z=fa[y],w=rs(y)==x;
if(nrt(y))ch[z][rs(z)==y]=x;fa[x]=z;
fa[ch[y][w]=ch[x][1-w]]=y;
ch[x][1-w]=y;fa[y]=x;
update(y);
}
void splay(int p){
int x=p,tp=0;
sta[++tp]=x;
while(nrt(x))sta[++tp]=x=fa[x];
while(tp)pushdown(sta[tp--]);x=p;
while(nrt(x)){
int y=fa[x],z=fa[y];
if(nrt(y))
(rs(z)==y)^(rs(y)==x)?rotate(x):rotate(y);
rotate(x);
}
update(x);
}
void access(int x){
for(int y=0;x;x=fa[y=x])
splay(x),rc=y,update(x);
}
void makeroot(int x){
access(x);splay(x);crv(x);
}
int calc(int x,int y){
makeroot(x);
access(y);
splay(y);
return c[y];
}
int main(){
int q;qr(q);
while(q--){
char s[2];scanf("%s",s);
if(s[0]=='B'){
n++;
int x;qr(x);
dx[n]=dy[n]=n;
c[n]=1;
if(x!=-1){
makeroot(x);
fa[n]=x;
int pre=calc(dx[x],dy[x]),t;
int hx=dx[x],hy=dy[x];
if((t=calc(dx[x],n))>pre){
pre=t;
hx=dx[x],hy=n;
}
if((t=calc(dy[x],n))>pre){
pre=t;
hx=n,hy=dy[x];
}
makeroot(x);
dx[x]=hx,dy[x]=hy;
}
}
else{
int x;qr(x);makeroot(x);
printf("%d\n",max(calc(x,dx[x]),calc(x,dy[x]))-1);
}
}
return 0;
}