题意:有n个点,有m个操作
操作:
Connect u v :把u和v连起来
Destroy u v:把u和v的边删除
Query u v:询问u和v是否联通
询问时可以用真实树中的树根是否一致来判断
参考代码:
#include<stdio.h>
#include<algorithm>
#define N 200005
using namespace std;
int rev[N],sz[N],ch[N][2],pre[N],st[N],t,n,val[N];
bool is_root(int x){return !pre[x]||(ch[pre[x]][0]!=x&&ch[pre[x]][1]!=x);}
bool side(int x){return ch[pre[x]][1]==x;}
void push_rev(int x)
{
if(!rev[x])return;
rev[x]=0;swap(ch[x][0],ch[x][1]);
if(ch[x][0])rev[ch[x][0]]^=1;
if(ch[x][1])rev[ch[x][1]]^=1;
}
void update(int x)
{
sz[x]=1;
if(ch[x][0])sz[x]+=sz[ch[x][0]];
if(ch[x][1])sz[x]+=sz[ch[x][1]];
}
void rotate(int x)
{
int y=pre[x],z=pre[y];
bool f=ch[y][1]==x;
if(!is_root(y))ch[z][ch[z][1]==y]=x;
ch[y][f]=ch[x][!f];ch[x][!f]=y;
pre[x]=z;pre[y]=x;pre[ch[y][f]]=y;
update(y);update(x);
}
void splay(int x)
{
st[t=1]=x;
for(int y=x;!is_root(y);st[++t]=y=pre[y]);
for(;t;t--)if(rev[st[t]])push_rev(st[t]);
while(!is_root(x))
{
if(!is_root(pre[x]))
{
if(side(x)==side(pre[x]))rotate(pre[x]);
else rotate(x);
}
rotate(x);
}
update(x);
}
void access(int x)
{
for(int t=0;x;ch[x][1]=t,t=x,x=pre[x])splay(x);
}
void make_root(int x)
{
access(x);
splay(x);
rev[x]^=1;
}
void link(int x,int y)
{
make_root(x);
pre[x]=y;
}
int findroot(int x)
{
access(x);
splay(x);
push_rev(x);
while(ch[x][0])push_rev(x),x=ch[x][0];
splay(x);
return x;
}
void cut(int x,int y)
{
make_root(x);
if(findroot(y)==x&&pre[y]==x&&!ch[y][0])
{
pre[y]=ch[x][1]=0;
update(x);
}
}
void path(int x,int y)
{
make_root(x);
access(y);
splay(y);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
char op[10];
int x,y;
for(int i=1;i<=m;i++)
{
scanf("%s%d%d",op,&x,&y);
if(op[0]=='Q')
{
if(findroot(y)==findroot(x))printf("Yes\n");
else printf("No\n");
}
else if(op[0]=='D')
{
cut(x,y);
}
else
{
link(x,y);
}
}
return 0;
}