luoguP2147 [SDOI2008]洞穴勘測

10分鐘一個,還是要多練練板子

#include<bits/stdc++.h>
#define MAXN 10005
using namespace std;

int n,m,tot;

struct node{int ch[2],f,res;}t[MAXN];
int pp(int rt){t[rt].res = (t[rt].res ^ 1) , swap(t[rt].ch[0] , t[rt].ch[1]);}
int push_down(int rt){
	if(!t[rt].res)return 0;
	pp(t[rt].ch[0]) , pp(t[rt].ch[1]);
	t[rt].res = 0;
}
int get(int rt){return (t[t[rt].f].ch[1] == rt);}
int checkrt(int rt){return (t[rt].f && (t[t[rt].f].ch[0] == rt || t[t[rt].f].ch[1] == rt));}
int rote(int rt){
	int ff = t[rt].f , gg = t[ff].f , d = get(rt) , cc = t[rt].ch[d ^ 1];
	if(checkrt(ff))t[gg].ch[get(ff)] = rt;
	t[rt].f = gg , t[ff].f = rt , t[rt].ch[d ^ 1] = ff , t[cc].f = ff , t[ff].ch[d] = cc;
}
int pull(int rt){
	if(checkrt(rt))pull(t[rt].f);
	push_down(rt);
}
int splay(int rt){
	pull(rt);
	for(int ff = t[rt].f ; checkrt(rt) ; rote(rt)){
		if(checkrt(ff = t[rt].f)){
			if(get(ff) == get(rt))rote(ff);
			else rote(rt);
		}
	}	
}

int access(int rt){for(int y = 0 ; rt ; rt = t[y = rt].f)splay(rt) , t[rt].ch[1] = y;}

int makert(int rt){
	access(rt);
	splay(rt);
	pp(rt);
}

int foundrt(int rt){
	access(rt);
	splay(rt);
	while(t[rt].ch[0])rt = t[rt].ch[0] , push_down(rt);
	return rt;
}

int split(int x , int y){
	makert(x);
	access(y);
	splay(y);
}

int link(int x , int y){
	if(foundrt(x) == foundrt(y))return 0;
	makert(x);
	t[x].f = y;
}

int cut(int x , int y){
	if(foundrt(x) != foundrt(y))return 0;
	makert(x);
	split(x , y);
	t[x].f = t[y].ch[0] = 0;
}

int main(){
	cin>>n>>m;
	for(int i = 1 ; i <= n ; i++){
		++tot;
		t[tot].ch[0] = t[tot].ch[1] = t[tot].f = t[tot].res = 0;
	}
	string tp;
	int x,y;
	for(int i = 1 ; i <= m ; i++){
		cin>>tp;
		scanf("%d%d" , &x , &y);
		if(tp == "Query"){
			if(foundrt(x) == foundrt(y))cout<<"Yes"<<endl;
			else cout<<"No"<<endl;
		}
		if(tp == "Connect"){
			link(x , y);
		}
		if(tp == "Destroy"){
			cut(x , y);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章