题目描述
题解
Link-Cut-Tree模板题。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int max_n=2e6+5;
int n,m,x,y;
int f[max_n],ch[max_n][2],size[max_n],reverse[max_n];
int strack[max_n];
char s[10];
inline int get(int x){
return ch[ f[x] ][1]==x;
}
inline void update(int x){
if (x){
size[x]=1;
if (ch[x][0]) size[x]+=size[ ch[x][0] ];
if (ch[x][1]) size[x]+=size[ ch[x][1] ];
}
}
inline void pushdown(int x){
if (x&&reverse[x]){
swap(ch[x][0],ch[x][1]);
if (ch[x][0]) reverse[ ch[x][0] ]^=1;
if (ch[x][1]) reverse[ ch[x][1] ]^=1;
reverse[x]=0;
}
}
inline int Is_Root(int x){
return ch[ f[x] ][0]!=x&&ch[ f[x] ][1]!=x;
}
inline void rotate(int x){
int old=f[x],oldf=f[old],which=get(x);
if (!Is_Root(old))
ch[oldf][ ch[oldf][1]==old ]=x;
f[x]=oldf;
ch[old][which]=ch[x][which^1];
f[ ch[old][which] ]=old;
ch[x][which^1]=old;
f[old]=x;
update(old);
update(x);
}
inline void splay(int x){
int top=0;
strack[++top]=x;
for (int i=x; !Is_Root(i); i=f[i])
strack[++top]=f[i];
for (int i=top; i>=1; --i) pushdown( strack[i] );
for (int fa; !Is_Root(x); rotate(x))
if (!Is_Root(fa=f[x]))
rotate( (get(x)==get(fa)) ?fa:x);
}
inline void Access(int x){
int t=0;
for (; x; t=x,x=f[x]){
splay(x);
ch[x][1]=t;
}
}
inline void Reverse(int x){
Access(x);
splay(x);
reverse[x]^=1;
}
inline int find(int x){
Access(x);
splay(x);
while (ch[x][0])
x=ch[x][0];
return x;
}
inline void Link(int x,int y){
Reverse(x);
f[x]=y;
splay(x);
}
inline void Cut(int x,int y){
Reverse(x);
Access(y);
splay(y);
ch[y][0]=f[x]=0;
}
int main(){
scanf("%d%d",&n,&m);
for (int i=1;i<=m;++i){
scanf("%s",s);
scanf("%d%d",&x,&y);
if (s[0]=='Q'){
if (find(x)==find(y))
printf("Yes\n");
else
printf("No\n");
}
if (s[0]=='C')
Link(x,y);
if (s[0]=='D')
Cut(x,y);
}
}
总结
花了挺长的时间学了LCT,还不是很熟练,还要继续写一些题来熟练。
给初学者的建议:
1、首先先学会链剖和splay,并能掌握它们的原理,熟练写模板。
2、了解LCT和链剖定义的不同,明确Access/Reverse操作各自的作用和原理。
3、在理解操作的原理之后,研究Link/Cut/Find操作如何将它们结合起来。