LCT入门(动态树)(点权)(边权)

本文介绍了LCT(Link Cut Tree)的基础知识和应用场景,包括在线链接与删除、查询连通性、维护链上信息等。重点讲解了点权和边权的操作,如access、makeroot、link、cut、split等功能,并提供了相关操作的代码示例,适用于动态维护树结构的问题。

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

LCT的用途:
1,在线链接link&cut(连接边,删除边)
2,查询连通性
3,维护链上信息
4,换根
5,维护子树信息。
等等:

基础知识:
1.伸展树(Splay Tree)
:支持链上求和,求最值,修改,等等操作,
2LCT(link cut tree):是一棵树,长这样:

在这里插入图片描述
这上面有一些粗一点的边,我们把它称为重边;还有一些细一点的,我们把它称为轻边

基本函数功能介绍:

access(x):x-根节点变成重边,专门用一棵splay维护
makeroot(x):将x变成整棵LCT树的根。
link(x, y):新建一条边,x-y链接起来;
cut(x,y):删除边x-y;
split(x,y):将x-y路径取出分离。求解u到v的路径上的节点权值和只需split(u,v),然后输出sum[v]即可。

rotate(x)/reverse(x):翻转x的子树:

下面来举一个直接套用模板的例子:
在这里插入图片描述
//在上面的代码中除了update(),pushdown()其他的都是模板。

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>

using namespace std;

inline int read()
{
   
  int x=0,f=1;char ch=getchar();
  while (!isdigit(ch)) {
   if (ch=='-') f=-1;ch=getchar();}
  while (isdigit(ch)) {
   x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
  return x*f;
}

const int maxn = 1e6+1e2;

int fa[maxn],ch[maxn][3]; //ch[i][0] -- 代表左孩子,ch[i][1]--代表右孩子; 
int rev[maxn],sum[maxn];    //sum[i]--表示i到根节点的异或和; 
int n,m;
int val[maxn];      //val--代表每一个点的权值。 
int st[maxn];

int son(int x)
{
   
	if (ch[fa[x]][0]==x) 
	  return 0;
	else return 1;
}

bool notroot(int x)
{
   
	return (ch[fa[x]][0]==x) || (ch[fa[x]][1]==x);
}

void update(int x)    //这是自己写的,在这个代码中是计算路径权值异或和,配合pushdown()函数。 
{
   
	sum[x]=sum[ch[x][0]]^sum[ch[x][1]]^val[x];
}

void reverse(int x)
{
   
	swap(ch[x][0],ch[x][1]);
	rev[x]^=1;
}
void pushdown(int x)//里面的内容也是自己编辑的。
{
   
	if (rev[x])
	{
   
		if (ch[x][0]) reverse(ch[x][0]);
		if (ch[x][1]) reverse(ch[x][1]);
		rev[x]=0;
	}
}

void rotate(int x)
{
   
	int y=fa[x],z=fa[y];
	int b=son(x),c=son(y);
	if(notroot(y)) ch[z][c]=x;
    fa[x]=z;
	ch[y][b]=ch[x][!b];
	fa[ch[x][!b]]=y;
	ch[x][!b]=y;
	fa[y]=x;
	update(y);
	update(x);
	//cout<<1<<endl;
}

void splay(int x)
{
   
	int y=x,cnt=0;
	st[++cnt]=y;
	while(notroot(y)){
   y=fa[y];st[++cnt]=y;}
	while (cnt) pushdown(st[cnt--]);
	while (notroot(x))
	{
   
		int y=fa[x],z=fa[y];
		int b=son(x),c=son(y);
		if (!notroot(y)) rotate(x);
		else
		//if (notroot(y))
		{
   
			if (b==c)
			{
   
				rotate(y);
				rotate(x);
			}
			else
			{
   
				rotate(x);
				rotate(x);
			}
		}
		//cout<<1<<endl;
	 } 
	 update(x);
}

void access(int x)
{
   
	for (int y=0;x;y=x,x=fa[x])
	{
   
		splay(x);
		ch[x][1]=y;
		update(x); 
	}
}

void makeroot(int x)
{
   
	access(x);
	//splay(x);
	reverse(x);
} 

int findroot(int x)
{
   
   access(x);
   splay(x);
   while (ch[x][0])
   {
   
   	  pushdown(x);
   	  x=ch[x][0];
   }
   //splay(x);
   return x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值