[BZOJ4668]冷战
并查集按秩合并的裸题。。。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=500005;
int fa[N],lastans,val[N],n,Q,u,v,opt,cnt,dep[N];
bool tong[N];
int find(int x) {
if(x==fa[x]) return x;
int f=find(fa[x]);
dep[x]=dep[fa[x]]+1;
return f;
}
void merge(int x,int y) {
++cnt;
x=find(x),y=find(y);
if(x==y) return;
if(dep[x]>dep[y]) swap(x,y);
fa[x]=y;
if(dep[x]==dep[y]) dep[y]++;
val[x]=cnt;
}
int find(int x,int y) {
int fx=find(x),fy=find(y);
lastans=0;
if(fx!=fy) return 0;
while(x!=y) {
if(dep[x]<dep[y]) swap(x,y);
lastans=max(lastans,val[x]);x=fa[x];
}
return lastans;
}
int main() {
scanf("%d%d",&n,&Q);
for(int i=1;i<=n;i++) fa[i]=i;
while(Q--) {
scanf("%d%d%d",&opt,&u,&v);
switch (opt) {
case 0:merge(u^lastans,v^lastans);break;
case 1:printf("%d\n",lastans=find(u^lastans,v^lastans));break;
}
}
return 0;
}
我是咸鱼。转载博客请征得博主同意Orz