题目大意
一个n个点的图,一开始没有任何边。要求在线支持
∙ link(u,v)连接(u,v)
∙ query(u,v)查询点对(u,v)最早在那一条边插入时联通
1≤n,m≤5×105
题目分析
LCT?Splay常数过大,只能拿80分。
满分做法并查集按秩合并:不采用路径压缩,而将深度小的合并到深度大的哪里,这样每次只有在两者深度相同时,最大深度才会+1,因此并查集深度始终是log2n的。记录每个点到父亲节点最早什么时候联通,查询的时候直接跳就好了。
时间复杂度O(mlog2n)。
代码实现
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cctype>
using namespace std;
int read()
{
int x=0,f=1;
char ch=getchar();
while (!isdigit(ch)) f=ch=='-'?-1:f,ch=getchar();
while (isdigit(ch)) x=x*10+ch-'0',ch=getchar();
return x*f;
}
const int N=500050;
int fa[N],d[N],t[N];
int ans,n,m,cnt;
bool vis[N];
int query(int x,int y)
{
int lca,z,ret=0;
for (z=x;z;z=fa[z]) vis[z]=true;
for (z=y;z&&!vis[z];) z=fa[z];
if (z)
{
for (lca=z,z=x;z!=lca;z=fa[z]) ret=max(ret,t[z]);
for (z=y;z!=lca;z=fa[z]) ret=max(ret,t[z]);
}
for (z=x;z;z=fa[z]) vis[z]=false;
return ret;
}
void link(int x,int y,int id)
{
int fx,fy,z;
for (z=x;z;z=fa[z]) fx=z;
for (z=y;z;z=fa[z]) fy=z;
if (fx==fy) return;
if (d[fx]<d[fy]) swap(fx,fy);
fa[fy]=fx,t[fy]=id,d[fx]=max(d[fx],d[fy]+1);
}
int main()
{
freopen("coldwar.in","r",stdin),freopen("coldwar.out","w",stdout);
n=read(),m=read();
for (int i=1;i<=n;i++) d[i]=1;
ans=0;
for (int i=1,op,u,v;i<=m;i++)
{
op=read(),u=read(),v=read();
u^=ans,v^=ans;
if (op) printf("%d\n",ans=query(u,v));
else link(u,v,++cnt);
}
fclose(stdin),fclose(stdout);
return 0;
}