其他分享
首页 > 其他分享> > 动态树之 Link Cut Tree 学习笔记

动态树之 Link Cut Tree 学习笔记

作者:互联网

LCT 题单做题记录

一、维护链信息

二、动态维护连通性&双联通分量

三、维护子树信息


LCT 板子代码

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

#define rep(i, a, b) for(register int i = a; i <= b; ++i)
#define ls t[x].ch[0]
#define rs t[x].ch[1]
const int maxn = 3e5 + 5;
int n, m;
struct node{
	int f, ch[2], sum, val;
	bool rev;
}t[maxn];

inline bool nrt(int p)
{
	int x = t[p].f;
	return (ls == p or rs == p);
}

inline void up(int x) {t[x].sum = t[ls].sum ^ t[rs].sum ^ t[x].val;}

inline void rv(int x) {swap(ls, rs); t[x].rev ^= 1;}

inline void dw(int x)
{
	if(!t[x].rev) return;
	if(ls) rv(ls); if(rs) rv(rs);
	t[x].rev = 0;
}

inline void rotate(int x)
{
	int y = t[x].f, z = t[y].f;
	int kx = (t[y].ch[1] == x), ky = (t[z].ch[1] == y), w = t[x].ch[!kx];
	if(nrt(y)) t[z].ch[ky] = x;
	t[x].ch[!kx] = y, t[y].ch[kx] = w;
	if(w) t[w].f = y;
	t[y].f = x, t[x].f = z;
	up(y), up(x);
}

inline void pushall(int x) {if(nrt(x)) pushall(t[x].f); dw(x);}

inline void splay(int x)
{
	pushall(x);
	while(nrt(x))
	{
		int y = t[x].f, z = t[y].f;
		if(nrt(y)) rotate((t[z].ch[1] == y) ^ (t[y].ch[1] == x) ? x : y);
		rotate(x);
	}
	up(x);
}

inline void access(int x)
{
	for(register int lst = 0; x; x = t[lst = x].f)
		splay(x), rs = lst, up(x);
}

inline void mkrt(int x) {access(x), splay(x), rv(x);}

inline int fndrt(int x)
{
	access(x), splay(x);
	while(ls) dw(x), x = ls;
	splay(x); return x;
}

inline void split(int x, int y) {mkrt(x), access(y), splay(y);}

inline void link(int x, int y) {mkrt(x); if(fndrt(y) != x) t[x].f = y;}

inline void cut(int x, int y)
{
	split(x, y);
	if(fndrt(y) == x and t[y].f == x and !t[y].ch[0])
		t[y].f = t[x].ch[1] = 0, up(x);
}

int main()
{
	scanf("%d%d", &n, &m);
	rep(i, 1, n) scanf("%d", &t[i].val);
	rep(i, 1, m)
	{
		int opt, x, y;
		scanf("%d%d%d", &opt, &x, &y);
		if(!opt) split(x, y), printf("%d\n", t[y].sum);
		if(opt == 1) link(x, y);
		if(opt == 2) cut(x, y);
		if(opt == 3) splay(x), t[x].val = y;
	}
	return 0;
}

标签:LCT,Cut,标记,Tree,三叉神经,Link,维护,节点,分量
来源: https://www.cnblogs.com/gsn531/p/16497413.html