题解:SP9577 DYNACON1 - Dynamic Tree Connectivity
离线的动态森林连通性。
离线的动态森林信息一般用 lct 维护,直接甩上去就行。
判断联通只需要 findRoot,看根一不一样。
/******************************
- @GavinCQTD
- "Dynamic Tree Connectivity"
- # https://www.spoj.com/problems/DYNACON1/
- 2000 ms
******************************/
#include <iostream>
#include <cassert>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
class LCT{
private:
struct Node{
int son[2],fa,val,sum;
bool rev;
Node():son(),fa(),val(),sum(),rev(){}
};
Node tree[100005];
bool get(int x){
return tree[tree[x].fa].son[1]==x;
}
bool isRoot(int x){
return tree[tree[x].fa].son[0]!=x&&tree[tree[x].fa].son[1]!=x;
}
void pushUp(int x){
tree[x].sum = tree[x].val^tree[tree[x].son[0]].sum
^tree[tree[x].son[1]].sum;
}
void pushDown(int x){
if(!tree[x].rev){
return;
}
swap(tree[x].son[0],tree[x].son[1]);
if(tree[x].son[0]){
tree[tree[x].son[0]].rev ^= 1;
}
if(tree[x].son[1]){
tree[tree[x].son[1]].rev ^= 1;
}
tree[x].rev = false;
}
void update(int x){
if(!isRoot(x)){
update(tree[x].fa);
}
pushDown(x);
}
void rotate(int x){
int y=tree[x].fa,z=tree[y].fa,c=get(x);
if(!isRoot(y)){
tree[z].son[get(y)] = x;
}
tree[tree[x].son[c^1]].fa = y;
tree[y].son[c] = tree[x].son[c^1];
tree[x].son[c^1] = y;
tree[y].fa = x;
tree[x].fa = z;
pushUp(y);
pushUp(x);
}
void access(int x){
for(int p=0;x!=0;p=x,x=tree[x].fa){
splay(x);
tree[x].son[1] = p;
pushUp(x);
}
}
void splay(int x){
update(x);
for(int f=tree[x].fa;!isRoot(x);rotate(x),f=tree[x].fa){
if(!isRoot(f)){
rotate(get(f)==get(x)?f:x);
}
}
}
void makeRoot(int x){
access(x);
splay(x);
tree[x].rev ^= 1;
}
void split(int x,int y){
makeRoot(x);
access(y);
splay(y);
}
public:
Node& operator[](int id){
return tree[id];
}
int find(int x){
access(x);
splay(x);
while(tree[x].son[0]!=0){
pushDown(x);
x = tree[x].son[0];
}
splay(x);
return x;
}
void link(int x,int y){
makeRoot(x);
if(find(y)!=x){
tree[x].fa = y;
}
}
void cut(int x,int y){
makeRoot(x);
if(find(y)==x&&tree[y].fa==x&&tree[y].son[0]==0){
tree[y].fa = 0;
tree[x].son[1] = 0;
pushUp(x);
}
}
void modify(int x,int v){
makeRoot(x);
splay(x);
tree[x].val = v;
}
int query(int x,int y){
split(x,y);
return tree[y].sum;
}
};
int n,m;
LCT lct;
int main(){
cin >> n >> m;
for(int i=1;i<=m;i++){
string op;
int a,b;
cin >> op >> a >> b;
if(op=="add"){
lct.link(a,b);
}
else if(op=="rem"){
lct.cut(a,b);
}
else{
cout << (lct.find(a)==lct.find(b)?"YES":"NO") << "\n";
}
}
return 0;
}