您的位置:首页 > 其它

bzoj2049: [Sdoi2008]Cave 洞穴勘测 LCT

2015-02-17 20:13 190 查看
由于并查集无法拆边所以考虑用LCT。询问的话首先把x移到LCT的根再把y和根联通。由于无法确定深度,所以两个都要往上遍历。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 200010
inline int getint()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m;
int next[maxn],tr[maxn][2],fa[maxn],siz[maxn],st[maxn];
bool rev[maxn];
inline bool isroot(int k)
{
return tr[fa[k]][0]!=k && tr[fa[k]][1]!=k;
}
void pushdown(int x)
{
int l=tr[x][0],r=tr[x][1];
if(rev[x])
{
rev[x]=0;rev[l]^=1;rev[r]^=1;
swap(tr[x][0],tr[x][1]);
}
}
void rotate(int &x)
{
int l,r,y,z;
y=fa[x];z=fa[y];
if(tr[y][0]==x) l=0;
else l=1; r=l^1;
if(!isroot(y))
{
if(tr[z][0]==y) tr[z][0]=x;
else tr[z][1]=x;
}
fa[x]=z;fa[y]=x;fa[tr[x][r]]=y;
tr[y][l]=tr[x][r];tr[x][r]=y;
}
void splay(int x)
{
int top=0;st[++top]=x;
for(int i=x;!isroot(i);i=fa[i])
{
st[++top]=fa[i];
}
for(int i=top;i;i--) pushdown(st[i]);
int y,z;
while(!isroot(x))
{
y=fa[x];z=fa[y];
if(!isroot(y))
{
if((tr[y][0]==x)^(tr[z][0]==y)) rotate(x);
else rotate(y);
}
rotate(x);
}
}
void access(int x)
{
int t=0;
while(x)
{
splay(x);
tr[x][1]=t;
t=x;x=fa[x];
}
}
void makeroot(int x)
{
access(x);splay(x);rev[x]^=1;
}
void link(int x,int y)
{
makeroot(x);fa[x]=y;splay(x);
}
void cut(int x,int y)
{
makeroot(x);access(y);splay(y);tr[y][0]=fa[x]=0;
}
bool query(int x,int y)
{
access(x);splay(x);
while(y)
{
if(y==x) return true;
else y=fa[y];
}
while(x)
{
if(y==x) return true;
else x=fa[x];
}
return false;
}
int main()
{
n=getint();
m=getint();
int a,b;
char str[10];
for(int i=1;i<=m;i++)
{
scanf("%s",str);
if(str[0]=='Q')
{
a=getint();b=getint();
if(query(a,b)) printf("Yes\n");
else printf("No\n");
}
if(str[0]=='D')
{
a=getint();b=getint();
cut(a,b);
}
if(str[0]=='C')
{
a=getint();b=getint();
link(a,b);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: