存在一个 的线段树分治 + 可撤销并查集的做法
更优秀的做法是 的 LCT 动态维护森林,这题作为 LCT 的模板题,只需要用到 link 和 cut 操作,即连接一条边 和 删除一条边。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int n,m;
inline int read(){
int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
}
struct LCT { //用splay维护原森林的连通,用到了splay的操作以及数组
int ch[maxn][2]; //ch[u][0] 表示 左二子,ch[u][1] 表示右儿子
int f[maxn]; //当前节点的父节点
int tag[maxn];
int top,sta[maxn];
inline bool get(int x){
return ch[f[x]][1] == x;
}
void init() {
memset(f,0,sizeof f);
memset(ch,0,sizeof ch);
memset(tag,0,sizeof tag);
}
inline void pushdown(int rt) {
if (!tag[rt]) return;
swap(ch[rt][0],ch[rt][1]);
if (ch[rt][0]) tag[ch[rt][0]] ^= 1;
if (ch[rt][1]) tag[ch[rt][1]] ^= 1;
tag[rt] = 0;
}
inline bool isroot(int x) {
return (ch[f[x]][0] != x) && (ch[f[x]][1] != x);
}
inline void rotate(int x) { //旋转操作,根据 x 在 f[x] 的哪一侧进行左旋和右旋
int old = f[x], oldf = f[old];
//pushdown(old); pushdown(x); //此处维护下推标记就炸了
int whichx = get(x);
if(!isroot(old)) ch[oldf][ch[oldf][1] == old] = x; //如果 old 不是根节点,就要修改 oldf 的子节点信息
ch[old][whichx] = ch[x][whichx ^ 1];
ch[x][whichx ^ 1] = old;
f[ch[old][whichx]] = old;
f[old] = x; f[x] = oldf;
}
inline void splay(int x) { //将 x 旋到所在 splay 的根
top = 0; sta[++top] = x;
for (int i = x; !isroot(i); i = f[i]) sta[++top] = f[i]; //在 splay 中维护 下推标记
while(top) pushdown(sta[top--]);
for(int fa = f[x]; !isroot(x); rotate(x), fa = f[x]) { //再把x翻上来
if(!isroot(fa)) //如果fa非根,且x 和 fa是同一侧,那么先翻转fa,否则先翻转x
rotate((get(x) == get(fa)) ? fa : x);
}
}
inline void access(int x) { //access操作将x 到 根路径上的边修改为重边
int lst = 0;
while(x > 0) {
splay(x);
ch[x][1] = lst;
lst = x; x = f[x];
}
}
inline void move_to_root(int x) { //将 x 移到 x 所在树的根(不是所在splay的根,所在splay只是一条重链)
access(x); splay(x); tag[x] ^= 1;
//将 x 移到 根之后 x 是深度最低的点,这条重链、这棵splay上所有点的深度颠倒,
//所有的点的左子树的点应该到右子树,因此要翻转这棵splay的左右子树
}
inline int findroot(int x) {
access(x);
splay(x);
int rt = x;
while(ch[rt][0]) rt = ch[rt][0];
return rt;
}
inline void link(int x,int y) {
move_to_root(x); f[x] = y; splay(x);
}
inline void cut(int x,int y) {
move_to_root(x); access(y);
splay(y); ch[y][0] = f[x] = 0;
}
}tree;
int x,y;
char op[10];
int main() {
n = read(); m = read();
tree.init();
while(m--) {
scanf("%s",op);
x = read(); y = read();
if (op[0] == 'Q') {
if (tree.findroot(x) == tree.findroot(y)) puts("Yes");
else puts("No");
} else if (op[0] == 'D') {
tree.cut(x,y);
} else {
tree.link(x,y);
}
}
return 0;
}