LCT模板题
顺便挂一个不错的LCT教程:link-cut trees
#include<cstdio>
#include<algorithm>
#define N 10005
using namespace std;
struct node
{
int fa, ch[2], lazy;
}t[N];
char s[10];
int stk[N], top;
void pushdown(int x)
{
if(t[x].lazy)
{
t[x].lazy=0;
swap(t[x].ch[0],t[x].ch[1]);
t[t[x].ch[0]].lazy^=1;
t[t[x].ch[1]].lazy^=1;
}
}
bool isroot(int x)
{
return t[t[x].fa].ch[0]!=x && t[t[x].fa].ch[1]!=x;
}
void rot(int x)
{
int fa=t[x].fa;
int gfa=t[fa].fa;
int t1=(t[fa].ch[0]!=x);
int t2=(t[gfa].ch[0]!=fa);
int ch=t[x].ch[t1^1];
if(!isroot(fa))t[gfa].ch[t2]=x;
t[ch].fa=fa;
t[x].fa=gfa;
t[x].ch[1^t1]=fa;
t[fa].fa=x;
t[fa].ch[t1]=ch;
}
void splay(int x)
{
stk[++top]=x;
for(int i = x; !isroot(i); i=t[i].fa)
stk[++top]=t[i].fa;
while(top)
pushdown(stk[top--]);
while(!isroot(x))
{
int fa=t[x].fa;
int gfa=t[fa].fa;
if(!isroot(fa))
(t[fa].ch[0]==x)^(t[gfa].ch[0]==fa)?rot(x):rot(fa);
rot(x);
}
}
void access(int x)
{
int temp=0;
while(x)
{
splay(x);
t[x].ch[1]=temp;
temp=x;
x=t[x].fa;
}
}
void makeroot(int x)
{
access(x);
splay(x);
t[x].lazy^=1;
}
int findroot(int x)
{
access(x);
splay(x);
int temp=x;
while(t[temp].ch[0])
temp=t[temp].ch[0];
return temp;
}
void link(int x, int y)
{
makeroot(x);
t[x].fa=y;
}
void cut(int x, int y)
{
makeroot(x);
access(y);
splay(y);//这里需要进行一次旋转,因为access前x和y是否属于同一个SplayTree会使x和y的相对位置不同
t[x].fa=t[y].ch[0]=0;
}
int main()
{
int n, m;
scanf("%d%d",&n,&m);
for(int i = 1; i <= m; i++)
{
int a, b;
scanf("%s%d%d",s,&a,&b);
if(s[0]=='Q')
{
if(findroot(a)==findroot(b))
printf("Yes\n");
else printf("No\n");
}
else if(s[0]=='C')
link(a,b);
else
cut(a,b);
}
}