BZOJ好了以后去交了这题,算是动态树补完
题目大意:
求一棵树上任意两点的连通性
这道题算是真真正正的link-cut tree了,之前的动态树题目都没有涉及link和cut操作
所以这道题让我发现了我在写cut过程中的一个错误,也让我更加深刻的体会到了link-cut tree的优美
对于修改,link cut即可
对于每个询问,看他们是否在同一棵树中
code:
//Lib #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<ctime> #include<iostream> #include<algorithm> #include<vector> #include<string> #include<queue> using namespace std; //Macro #define rep(i,a,b) for(int i=a,tt=b;i<=tt;++i) #define rrep(i,a,b) for(int i=a,tt=b;i>=tt;--i) #define erep(i,e,x) for(int i=x;i;i=e[i].next) #define irep(i,x) for(__typedef(x.begin()) i=x.begin();i!=x.end();i++) #define read() (strtol(ipos,&ipos,10)) #define sqr(x) ((x)*(x)) #define pb push_back #define PS system("pause"); typedef long long ll; typedef pair<int,int> pii; const int oo=~0U>>1; const double inf=1e20; const double eps=1e-6; string name="",in=".in",out=".out"; //Var struct T { int LC,RC,FA; bool REV; #define lc(x) tree[x].LC #define rc(x) tree[x].RC #define fa(x) tree[x].FA #define rev(x) tree[x].REV }tree[10008]; int n,m; void Update(int x) { if(rev(x)) { swap(lc(x),rc(x));rev(x)^=1; rev(lc(x))^=1;rev(rc(x))^=1; } } void Zig(int x) { int y=fa(x),z=fa(y); if(lc(z)==y)lc(z)=x;else if(rc(z)==y)rc(z)=x;fa(x)=z; fa(rc(x))=y;lc(y)=rc(x);fa(y)=x;rc(x)=y; Update(y); } void Zag(int x) { int y=fa(x),z=fa(y); if(lc(z)==y)lc(z)=x;else if(rc(z)==y)rc(z)=x;fa(x)=z; fa(lc(x))=y;rc(y)=lc(x);fa(y)=x;lc(x)=y; Update(y); } bool isRoot(int x){return lc(fa(x))!=x&&rc(fa(x))!=x;} void Push_Down(int x){if(!isRoot(x))Push_Down(fa(x));Update(x);} void Splay(int x) { Push_Down(x); for(int y,z;!isRoot(x);) { y=fa(x);z=fa(y); if(isRoot(y)) if(lc(y)==x)Zig(x); else Zag(x); else if(lc(z)==y) if(lc(y)==x)Zig(y),Zig(x); else Zag(x),Zig(x); else if(rc(y)==x)Zag(y),Zag(x); else Zig(x),Zag(x); } Update(x); } void Expose(int x){for(int y=0;x;x=fa(x)){Splay(x);rc(x)=y;Update(x);y=x;}} void Evert(int x){Expose(x);Splay(x);rev(x)^=1;} void Link(int x,int y){Evert(x);fa(x)=y;} void Cut(int x,int y){Expose(y);Splay(x);if(fa(x)==y)fa(x)=0;else{Expose(x);Splay(y);fa(y)=0;}} bool Query(int a,int b) { int x=a,y=b; Expose(y); for(y=0;x;x=fa(x)){Splay(x);if(!fa(x))break;y=x;} for(;rc(x);x=rc(x)); return x==b; } void Work() { int a,b;char ch[10]; rep(i,1,m) { scanf("%s%d%d",ch,&a,&b); if(ch[0]=='C')Link(a,b); if(ch[0]=='D')Cut(a,b); if(ch[0]=='Q')puts(Query(a,b)?"Yes":"No"); } } int main() { // freopen((name+in).c_str(),"r",stdin); // freopen((name+out).c_str(),"w",stdout); scanf("%d%d",&n,&m); Work(); return 0; }