[SDOI2008] 洞穴勘测【LCT】

>Link

luogu P2147


>Description

要求支持连边、删边、查询两点是否连通三种操作


>解题思路

LCT裸题


>代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 10010
using namespace std;

struct node
{
	int son[2], f, lazy;
} t[N];
int n, m;

void pushdown (int x)
{
	if (!t[x].lazy) return;
	swap (t[x].son[0], t[x].son[1]);
	if (t[x].son[0]) t[t[x].son[0]].lazy ^= 1;
	if (t[x].son[1]) t[t[x].son[1]].lazy ^= 1;
	t[x].lazy = 0;
}
int identity (int x)
{
	if (t[t[x].f].son[0] == x) return 0;
	if (t[t[x].f].son[1] == x) return 1;
	return -1;
}
void pushall (int x)
{
	if (identity (x) != -1) pushall (t[x].f);
	pushdown (x);
}
void rotate (int x)
{
	int y = t[x].f, z = t[y].f;
	int k = identity (x), kk = identity (y);
	t[y].son[k] = t[x].son[k ^ 1];
	t[t[x].son[k ^ 1]].f = y;
	t[x].son[k ^ 1] = y, t[y].f = x;
	if (kk != -1) t[z].son[kk] = x;
	t[x].f = z;
}
void splay (int x)
{
	pushall (x);
	int k, kk, y, z;
	while (identity (x) != -1)
	{
		y = t[x].f, z = t[y].f;
		k = identity (x), kk = identity (y);
		if (kk != -1)
		{
			if (k == kk) rotate (y);
			else rotate (x);
		}
		rotate (x);
	}
}
void access (int x)
{
	int pre = 0;
	while (x)
	{
		splay (x);
		t[x].son[1] = pre;
		pre = x;
		x = t[x].f;
	}
}
void makeroot (int x)
{
	access (x);
	splay (x);
	t[x].lazy ^= 1;
}
void connect (int u, int v)
{
	makeroot (u);
	t[u].f = v;
}
void cut (int u, int v)
{
	makeroot (u);
	access (v);
	splay (v);
	if (t[u].f != v || t[u].son[1]) return;//
	t[v].son[0] = t[u].f = 0;
}
int findroot (int x)
{
	access (x);
	splay (x);
	while (t[x].son[0]) x = t[x].son[0];
	splay (x); 
	return x;
}

int main()
{
	string s; int u, v;
	scanf ("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
	  t[i].son[0] = t[i].son[1] = t[i].f = t[i].lazy = 0;
	while (m--)
	{
		cin >> s;
		scanf ("%d%d", &u, &v);
		if (s == "Connect") connect (u, v);
		else if (s == "Destroy") cut (u, v);
		else
		{
			if (findroot (u) == findroot (v))
			  printf ("Yes\n");
			else printf ("No\n");
		}
	} 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值