[loj6038]「雅礼集训 2017 Day5」远行 lct+并查集

时间:2023-03-09 20:00:32
[loj6038]「雅礼集训 2017 Day5」远行 lct+并查集

给你 n 个点,支持 m 次操作,每次为以下两种:连一条边,保证连完后是一棵树/森林;询问一个点能到达的最远的点与该点的距离。强制在线。

n≤3×10^5 n≤3×10^5 ,m≤5×10^5 m≤5×10^5 。

我们知道与一个点距离最大的点为任意一个直径的两个端点之一。

两棵树之间连一条边,新树直径的两个端点一定为第一棵树直径的两个端点和第二棵树直径的两个端点这四者中之二。

于是我们可以用lct和并查集来维护树的直径的两个端点。

 #include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<cstdio>
#include<algorithm>
#define fa(x) t[x].fa
#define s(x,y) t[x].son[y]
#define maxn 305050
using namespace std;
inline int read() {
int x=,f=;char ch=getchar();
for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-;
for(;isdigit(ch);ch=getchar()) x=x*+ch-'';
return x*f;
}
int type;
int n,q;
struct LCT {
int f[maxn],px[maxn],py[maxn];
int find(int x) {return x==f[x]?f[x]:f[x]=find(f[x]);}
struct Tree {int son[],fa,w,rev;}t[maxn];
bool isrt(int x) {return s(fa(x),)!=x&&s(fa(x),)!=x;}
void pushup(int x) {t[x].w=t[s(x,)].w+t[s(x,)].w+;}
void pushdown(int x) {
if(t[x].rev) {
swap(s(x,),s(x,));
t[s(x,)].rev^=;t[s(x,)].rev^=;
t[x].rev=;
}
}
void push(int x) {
if(!isrt(x)) push(fa(x));
pushdown(x);
}
void rotate(int x) {
int y=fa(x),z=fa(y);
int l=s(y,)==x,r=l^;
if(!isrt(y)) s(z,s(z,)==y)=x;
fa(x)=z;fa(y)=x;fa(s(x,r))=y;
s(y,l)=s(x,r);s(x,r)=y;
pushup(y);pushup(x);
}
void splay(int x) {
push(x);
while(!isrt(x)) {
int y=fa(x),z=fa(y);
if(!isrt(y)) {
if(s(z,)==y^s(y,)==x) rotate(x);
else rotate(y);
}
rotate(x);
}
}
void access(int x) {for(int pre=;x;pre=x,x=fa(x)) {splay(x);s(x,)=pre;pushup(x);}}
void makert(int x) {access(x);splay(x);t[x].rev^=;}
int dis(int u,int v) {makert(u);access(v);splay(v);return t[v].w;}
void link(int u,int v) {
int fx=find(u),fy=find(v);
if(fx!=fy) {
makert(u);fa(u)=v;
int a=,b,c;
if(dis(px[fx],py[fx])>a) a=dis(px[fx],py[fx]),b=px[fx],c=py[fx];
if(dis(px[fy],py[fy])>a) a=dis(px[fy],py[fy]),b=px[fy],c=py[fy];
if(dis(px[fx],py[fy])>a) a=dis(px[fx],py[fy]),b=px[fx],c=py[fy];
if(dis(px[fx],px[fy])>a) a=dis(px[fx],px[fy]),b=px[fx],c=px[fy];
if(dis(py[fx],px[fy])>a) a=dis(py[fx],px[fy]),b=py[fx],c=px[fy];
if(dis(py[fx],py[fy])>a) a=dis(py[fx],py[fy]),b=py[fx],c=py[fy];
f[fx]=fy;px[fy]=b;py[fy]=c;
}
}
int query(int u) {
int x=find(u);
return max(dis(px[x],u),dis(py[x],u));
}
}lct;
int main() {
type=read();
n=read(),q=read();
for(int i=;i<=n;i++) lct.f[i]=lct.px[i]=lct.py[i]=i;
int lastans=;
while(q--) {
int t=read();
if(t==) {
int u=read()^(lastans*type),v=read()^(lastans*type);
lct.link(u,v);
}
else {
int u=read()^(lastans*type);
lastans=lct.query(u)-;
printf("%lld\n",lastans);
}
}
}