【LCT】P2147 [SDOI2008]洞穴勘测

本文详细介绍了一道LCT(链剖割树)的模板题,通过具体代码解释了LCT的数据结构、翻转操作、旋转操作、伸展操作、路径访问、根节点查找、链接和切割等核心操作,为读者提供了深入理解LCT算法的机会。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一道LCT的题目

就是模板

 

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5;
int n,m;
struct lct
{
	struct node
	{
		int fa,ch[2],rev;
		node() {fa=ch[0]=ch[1]=rev=0;}
	}tree[maxn];
	int top,res[maxn];
	#define ls(x) tree[x].ch[0]
	#define rs(x) tree[x].ch[1]
	int isroot(int x) {return tree[x].fa && (ls(tree[x].fa)==x || rs(tree[x].fa)==x);}
	void rev(int x)
	{
		swap(ls(x),rs(x));
		tree[x].rev^=1;
	}
	void pushdown(int x)
	{
		if(!tree[x].rev) return ;
		if(ls(x)) rev(ls(x));
		if(rs(x)) rev(rs(x));
		tree[x].rev^=1;
	}
	void rotate(int x)
	{
		int y=tree[x].fa,z=tree[y].fa;
		int k=(x==ls(tree[x].fa)),w=tree[x].ch[k];
		if(isroot(y)) tree[z].ch[y==rs(tree[y].fa)] =x;
		tree[x].ch[k]=y; tree[y].ch[!k]=w;
		tree[y].fa=x; tree[x].fa=z;
		if(w) tree[w].fa=y;
	}
	void splay(int x)
	{
		int tmp=x;
		res[top=1]=tmp;
		while(isroot(tmp)) res[++top]=tree[tmp].fa,tmp=tree[tmp].fa;
		while(top) pushdown(res[top]),top--;
		while(isroot(x))
		{
			if(isroot(tree[x].fa)) rotate((x==rs(tree[x].fa))^(tree[x].fa==rs(tree[tree[x].fa].fa))?x:tree[x].fa);
			rotate(x);
		}
	}
	void access(int x)
	{
		for(int y=0;x;y=x,x=tree[x].fa)
		{
			splay(x); rs(x)=y;
		}
	}
	void makeroot(int x)
	{
		access(x); splay(x); rev(x);
	}
	int findroot(int x)
	{
		access(x); splay(x); pushdown(x);
		while(ls(x))
		{
			x=ls(x); pushdown(x);
		 } 
		 return x;
	}
	void link(int x,int y)
	{
		if(findroot(x)==findroot(y)) return;
		makeroot(x); tree[x].fa=y;
	}
	void cut(int x,int y)
	{
		makeroot(x); access(y); splay(y);
		if(ls(y)==x) tree[x].fa=ls(y)=0;
	}
}LCT;
int main()
{
	freopen("a.in","r",stdin);
	freopen("a.out","w",stdout);
	scanf("%d%d",&n,&m);
	char op[20];
	int x,y;
	for(int i=1;i<=m;i++)
	{
		scanf("%s",op);
		scanf("%d%d",&x,&y);
		if(op[0]=='C') LCT.link(x,y);
		if(op[0]=='D') LCT.cut(x,y);
		if(op[0]=='Q')
		{
			if(LCT.findroot(x)==LCT.findroot(y))
				printf("Yes\n");
			else printf("No\n");
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值