[BZOJ2049]Cave 洞穴勘测 && 动态树

动态树模板题 用动态树维护连通性 加边什么的就那样

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
#include<map>
#define SF scanf
#define PF printf
using namespace std;
typedef long long LL;
const int MAXN = 100000;
int rt[MAXN+10];
struct LCT {
	int fa[MAXN+10], ch[MAXN+10][2];
	bool rev[MAXN+10];
	bool isroot(int x) {
		return ch[fa[x]][0] != x && ch[fa[x]][1] != x;
	}
	void up(int x) { }
	void push_down(int x) {
		int &ls = ch[x][0], &rs = ch[x][1];
		if(rev[x]) {
			rev[x] ^= 1; rev[ls] ^= 1; rev[rs] ^= 1;
			swap(ls, rs);
		}
	}
	void Rotate(int x) {
		int y = fa[x], z = fa[y];
		bool d = ch[y][0] == x;
		if(!isroot(y)) ch[z][y == ch[z][1]] = x;
		fa[x] = z; fa[y] = x; fa[ch[x][d]] = y;
		ch[y][!d] = ch[x][d]; ch[x][d] = y;
		up(y);
	}
	void splay(int x) {
		int top = 0; rt[++top] = x;
		for(int i = x; !isroot(i); i = fa[i]) rt[++top] = fa[i];
		for(int i = top; i; i--) push_down(rt[i]);
		while(!isroot(x)) {
			int y = fa[x], z = fa[y];
			if(!isroot(y)) {
				if(ch[y][0] == x ^ ch[z][0] == y) Rotate(x);
				else Rotate(y);
			}
			Rotate(x);
		}
		up(x);
	}
	void access(int x) {
		int t = 0;
		while(x) {
			splay(x);
			ch[x][1] = t;
			t = x; x = fa[x];
		}
	}
	void makeroot(int x) {
		access(x); splay(x); rev[x] ^= 1;
	}
	void link(int x, int y) {
		makeroot(x); fa[x] = y; splay(x);
	}
	void cut(int x, int y) {
		makeroot(x); access(y); splay(y); ch[y][0] = fa[x] = 0;
	}
	int find(int x) {
		access(x); splay(x);
		int y = x;
		while(ch[y][0]) y = ch[y][0];
		return y;
	}
} sp;
int n, m;
int main() {
    char s[10];
    SF("%d%d", &n, &m);
    for(int i = 1; i <= m; i++) {
		SF("%s", s);
		int x, y; SF("%d%d", &x, &y);
		if(s[0] == 'C') sp.link(x, y);
		else if(s[0] == 'D') sp.cut(x, y);
		else {
			if(sp.find(x) == sp.find(y)) puts("Yes");
			else puts("No");
		}
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值