跳到正文

个人记录

平衡树学习笔记

feather02约 23 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月22日
篇幅
约 23 分钟

版本

  1. v2当前
  2. v1

平衡树学习笔记

1.BST(二叉搜索树)

顾名思义,它是一棵二叉树。

它满足一个性质:每一个节点的权值大于它的左儿子,小于它的右儿子。

那么根据性质,可以得到该节点左子树里的所有值都比它小,右子树的都比它大。

而平衡树都是基于BST的。

为什么叫做平衡树?对于数的操作可能会破坏BST的性质,这时会进行另外的操作,保持它的性质。

为什么要用BST?对于一棵BST,每一次的操作,都相当于进行一次二分,时间复杂度可以降到log级别。

BST的性质

一棵二叉树,树上每个节点有一个关键值。对于树中任意一个节点:

节点的关键值大于等于左子树中所有节点的关键值。

节点的关键值小于等于右子树中所有节点的关键值。

显然,树的中序遍历是一个关键值递增的序列。

BST的建立

有一个递增序列,建立一个 BST 使得 BST 的中序遍历的关键值是这个 序列。

为了减少边界处的特殊情况,在序列开头加入 −∞,序列末尾加入 ∞。

找到序列中点作为根,递归建立左半区间作为左子树,递归建立右半区 间作为右子树。

BST的插入

在 BST 上查找值,到了空节点就把插入的值填进去。

BST的节点删除

在 BST 上查找值,找到了节点 p。

p 子节点个数不足 2 个。直接删除,子节点代替 p 的位置。

否则,求出 p 的后继 x(这里直接跳一次右儿子后一直跳左儿子), x 一定没有左子树,于是可以删除 x,把真正的 x 移到 p 上。

2.Splay

通过旋转操作 rotate 保持树的平衡。还有一个操作把某个节点旋转到根 Splay。其余操作直接用BST的做法。注意!!每次查询完都要 Splay 一下,这样才能保证复杂度。

基本变量

C++
int n,m;
int fa[N],ch[N][2],siz[N],rev[N],rt;
/*fa记录每个点的父亲,
ch[i][0]表示i的左儿子,ch[i][1]表示i的右儿子,
siz[i]表示以i为根的子树大小,rev是翻转标记数组,rt是树根*/

rotate

会画这张图,代码就很好写了

1.改 x 的父亲。 2.连直线边。 3.连曲线边。

把节点 p 旋转成 x 的儿子,旋转到根的话 x = 0。

只要 p 没到 x 就旋转。

一种情况需要特判:如果 p 和 p 的父亲和 p 的父亲的父亲三点共线,需要先旋转一下 p 的父亲。

codeP3391 【模板】文艺平衡树

C++
#include <iostream>
#include <cstdio>
#include <iomanip>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <cctype>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <map>
#include <set>

#define IOS ios::sync_with_stdio(false)
#define TIEI std::cin.tie(nullptr)
#define TIEO std::cout.tie(nullptr)
#define INF 0x7fffffff
#define RE register
#define forup(i,o,n) for(register long long i=o;i<=n;i++)
#define fordown(i,o,n) for(register long long i=o;i>=n;i--)
#define Max(a,b,c) max(a,(max(b,c)))
#define pii pair<int,int>
#define kp make_pair
#define fi first
#define se second
#define IT iterator
#define pb push_back
#define Ls(a) a<<1
#define Rs(a) a<<1|1

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef __int128 Int;
const int N=1e5+10;
const int M=2e5+10;
const LL MOD=1000007;


LL read()
{
	LL x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9')
	{
		if(ch=='-')
			f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
		x=(x<<3)+(x<<1)+(LL)(ch-'0'),ch=getchar();
	return x*f;
}

void write(LL n)
{
	if(n<0)
		putchar('-'),
		n=-n;
	if(n>=10)
		write(n/10);
	putchar(n%10+'0');
}

void writes(LL n)
{
	write(n); putchar(' ');
}

void writee(LL n)
{
	write(n); puts("");
}


int n,m;
int fa[N],ch[N][2],siz[N],rev[N],rt;


inline void pushup(int i)
{
	siz[i]=siz[ch[i][0]]+siz[ch[i][1]]+1;
}

inline void pushdown(int i)
{
	if(rev[i])
	{
		swap(ch[i][0],ch[i][1]);
		rev[ch[i][0]]^=1;rev[ch[i][1]]^=1;rev[i]=0;
	}
}

inline void rotate(int x,int &k)
{
	int y=fa[x],z=fa[y],kind;
	ch[y][0]==x ? kind=1 : kind=0;
	if(y==k)
		k=x;
	else
		ch[z][0]==y ? ch[z][0]=x : ch[z][1]=x;
	ch[y][kind^1]=ch[x][kind];
	fa[ch[y][kind^1]]=y;
	ch[x][kind]=y; fa[y]=x; fa[x]=z;
	pushup(x); pushup(y);
}

inline void splay(int x,int &k)
{
	while(x!=k)
	{
		int y=fa[x],z=fa[y];
		if(y!=k)
			(ch[y][0]==x)^(ch[z][0]==y) ? rotate(x,k) : rotate(y,k);
		rotate(x,k);
	}
}

void build(int l,int r,int k)
{
	if(l>r)
		return ;
	int mid=(l+r)>>1;
	mid<k ? ch[k][0]=mid : ch[k][1]=mid;
	fa[mid]=k;siz[mid]=1;
	if(l==r)
		return ;
	build(l,mid-1,mid); build(mid+1,r,mid);
	pushup(mid);
}

int Find(int x,int k)
{
	pushdown(x);
	int si=siz[ch[x][0]];
	if(k==si+1)
		return x;
	if(k<=si)
		return Find(ch[x][0],k);
	return Find(ch[x][1],k-si-1);
}

inline void rever(int l,int r)
{
	int x=Find(rt,l),y=Find(rt,r+2);
	splay(x,rt); splay(y,ch[x][1]);
	rev[ch[y][0]]^=1;
}


int main()
{
	n=read();m=read();
	rt=(n+3)>>1;
	build(1,n+2,rt);
	for(RE int i=1;i<=m;i++)
	{
		int l=read(),r=read();
		rever(l,r);
	}
	for(RE int i=2;i<=n+1;i++)
		writes(Find(rt,i)-1);
	return 0;
}

FHQ-Treap

Treap 的名字取自 Tree + Heap,Tree 即是之前讲的 BST。此外每个点还有一个优先值 pri 是随机给出的,同时还要求 Treap 满足子树内节点的优先值必须大于等于当前节点,这样借助随机的力量保证的 BST的平衡。

Treap 的基本操作有 Split 和 Merge。

基本变量

C++
int ch[N][2],val[N],pri[N],siz[N];
/*ch同上,val点权,pri优先值,siz同上*/

Split

给出一个关键值 v,将 Treap 分成两棵 Treap。第一棵满足所有 关键值小于等于 v,第二棵满足所有关键值大于 v。

即根节点关键值为 p。

v < p 那么根和右子树都在第二棵树中,继续递归分裂左子树。

v ≥ p 那么根和左子树都在第一棵树中,继续递归分裂右子树。

Merge

有两棵 Treap,其中第一棵的关键值全部小于等于第二棵的关 键值,将这两棵 Treap 合并成一棵。

两棵树的根分别为 x,y,关键值为 key。

pri [x] < pri [y]那么把 x 作为新树的根,递归合并 x 的右子树和 y 整棵树。

pri [x] ≥ pri [y]那么把 y 作为新树的根,递归合并 x 的整棵树和 y 的左子树。

操作

插入 v:按照 v 分裂,然后依次合并第一棵树,v,第二棵树。

删除 v:按照 v − 1,v 分裂,然后依次合并第一棵树,第二棵树的左子树,第二棵树的右子树,第三棵树。

查询 v 的排名:按照 v − 1 分裂,答案即为第一棵树的 siz 加一。

codeP3369 【模板】普通平衡树

C++
#include <bits/stdc++.h>

#define INF 0x7fffffff
#define RE register
#define pii pair<int,int>
#define kp make_pair
#define pb push_back
#define fi first
#define se second
#define IT iterator
#define root 1, n, 1
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#define lowbit(x) x & -x
#define debug1 puts("\nI love Elysia forever!")
#define debug2 puts("\nI love sinon forever!")
#define debug3 puts("\nI love Skuld forever!")
#define debug4 puts("\nI love Chtholly forever!")

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 1e5 + 10;
const int M = 1e5 + 10;
const int LOG = 20;
const LL MOD = 1e9 + 7;


LL read()
{
	LL x = 0, f = 1; char ch = getchar();
	while (ch < '0' || ch > '9')
	{
		if (ch == '-')
			f = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9')
		x = (x << 3) + (x << 1) + (LL)(ch - '0'), ch = getchar();
	return x * f;
}

void write(LL n)
{
	if (n < 0)
		putchar('-'),
		n = -n;
	if (n >= 10)
		write(n / 10);
	putchar(n % 10 + '0');
}

inline void writee(LL n)
{
	write(n); puts("");
}

inline void writes(LL n)
{
	write(n); putchar(' ');
}


int n;
int rt, tot;
int wei[N], val[N], siz[N], ch[N][2];

int newnode(int v)
{
	wei[++tot] = rand();
	val[tot] = v;
	siz[tot] = 1;
	return tot;
}

void pushup(int rt)
{
	siz[rt] = siz[ch[rt][0]] + siz[ch[rt][1]] + 1;
}

int merge(int x, int y)
{
	if (!x || !y)
		return x | y;
	if (wei[x] < wei[y])
	{
		ch[x][1] = merge(ch[x][1], y);
		pushup(x);
		return x;
	}
	else
	{
		ch[y][0] = merge(x, ch[y][0]);
		pushup(y);
		return y;
	}
}

void split(int p, int v, int &x, int &y)
{
	if (!p)
	{
		x = y = 0;
		return;
	}
	if (v < val[p])
	{
		y = p;
		split(ch[p][0], v, x, ch[p][0]);
	}
	else
	{
		x = p;
		split(ch[p][1], v, ch[p][1], y);
	}
	pushup(p);
}

int kth(int p, int k)
{
	if (siz[ch[p][0]] + 1 == k)
		return val[p];
	if (k <= siz[ch[p][0]])
		return kth(ch[p][0], k);
	else
		return kth(ch[p][1], k - siz[ch[p][0]] - 1);
}


int main()
{
	srand(time(0));
	n = read();
	for (int _ = 1; _ <= n; ++_)
	{
		int opt = read(), v = read(), x, y, z;
		switch (opt)
		{
			case 1:
				split(rt, v, x, y);
				rt = merge(merge(x, newnode(v)), y);
				break;
			case 2:
				split(rt, v, x, z);
				split(x, v - 1, x, y);
				rt = merge(merge(x, ch[y][0]), merge(ch[y][1], z));
				break;
			case 3:
				split(rt, v - 1, x, y);
				writee(siz[x] + 1);
				rt = merge(x, y);
				break;
			case 4:
				writee(kth(rt, v));
				break;
			case 5:
				split(rt, v - 1, x, y);
				z = x;
				while (ch[z][1])
					z = ch[z][1];
				writee(val[z]);
				rt = merge(x, y);
				break;
			case 6:
				split(rt, v, x, y);
				z = y;
				while (ch[z][0])
					z = ch[z][0];
				writee(val[z]);
				rt = merge(x, y);
		}
	}
	return 0;
}

LCT

类比树链剖分,树上每个节点都有最多一个实儿子,不一定是重儿子, 实儿子是可以变的。到实儿子的边就是实边,连在一起形成实链。一样 的拿数据结构维护实链的信息。

最重要的操作 Access(x):把 x 到根的路径变成实链。

这样询问一条链就把它变成实链就很方便了。

对每条实链使用 Splay 按照深度作为关键值维护,这个 Splay 的根的父亲指向实链在树上真实的父亲(是一条虚边,父亲不记录儿子,但是儿子记录父亲)。

Access

把 x 实儿子变成虚儿子:把 x 旋转到根后,断开 x 的右子树。

把边 (x,y) 变成实边:把 x 的右子树连上 y 所在 splay 的根。

Access(x) 从 x 向实际树根依次断边连边。

其他常用操作

1.makeroot(x) 把 x 变成实际树的根: Access(x) 然后交换 x 的左右子树(打上区间翻转标记)。

注意 pushdown,splay 前要先对整条到根的链 pushdown。

2.link(x,y) 在实际树上连接边 (x,y): makeroot(x) 后把 x 的父亲设为 y(连接虚边)。

3.cut(x,y) 断开实际树上的边 (x,y): makeroot(x) Access(y) Splay(y) 然后断开 y 的左子树。

4.find(x) 找到 x 所在实际树的根: Access(x) splay(x) 后一直跳 x 的左儿子直到跳不动。

注意 splay 任何向下询问发生后查询到的点都要 splay 到根保证复杂度。

5.query(x,y) 查询实际树上路径 (x,y) 的信息: makeroot(x) Access(y) Splay(y) 然后信息就存在 y 上。

C++
#include <bits/stdc++.h>

#define INF 0x7fffffff
#define RE register
#define pii pair<int,int>
#define kp make_pair
#define pb push_back
#define fi first
#define se second
#define IT iterator
#define root 1, n, 1
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#define lowbit(x) x & -x
#define debug1 puts("I love Elysia forever!")
#define debug2 puts("I love sinon forever!")
#define debug3 puts("I love Skuld forever!")
#define debug4 puts("I love Chtholly forever!")

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int N = 3e5 + 10;
const int M = 1e5 + 10;
const int LOG = 20;
const LL MOD = 1e9 + 7;


LL read()
{
	LL x = 0, f = 1; char ch = getchar();
	while (ch < '0' || ch > '9')
	{
		if (ch == '-')
			f = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9')
		x = (x << 3) + (x << 1) + (LL)(ch - '0'), ch = getchar();
	return x * f;
}

void write(LL n)
{
	if (n < 0)
		putchar('-'),
		n = -n;
	if (n >= 10)
		write(n / 10);
	putchar(n % 10 + '0');
}

inline void writee(LL n)
{
	write(n); puts("");
}

inline void writes(LL n)
{
	write(n); putchar(' ');
}


int n, m;
int col[N], fa[N], ch[N][2], s[N], a[N];
stack <int> st;

bool getson(int p)
{
	return ch[fa[p]][1] == p;
}

bool isroot(int p)
{
	return ch[fa[p]][getson(p)] != p;
}

void pushdown(int p)
{
	if (!col[p])
		return;
	swap(ch[p][0], ch[p][1]);
	col[ch[p][0]] ^= 1;
	col[ch[p][1]] ^= 1;
	col[p] = 0;
}

void pushup(int p)
{
	st.push(p);
	for (int i = p; !isroot(i); i = fa[i])
		st.push(fa[i]);
	while (!st.empty())
		pushdown(st.top()),
		st.pop();
}

void Assert(int p)
{
	s[p] = s[ch[p][0]] ^ s[ch[p][1]] ^ a[p];
}

void rotate(int p)
{
	int f = fa[p], g = fa[f], r = getson(p);
	if (!isroot(f))
		ch[g][getson(f)] = p;
	fa[p] = g;
	ch[f][r] = ch[p][r ^ 1];
	if (ch[f][r])
		fa[ch[f][r]] = f;
	ch[p][r ^ 1] = f;
	fa[f] = p;
	Assert(f); Assert(p);
}

void splay(int p)
{
	pushup(p);
	for (; !isroot(p); rotate(p))
		if (!isroot(fa[p]))
			rotate(getson(fa[p]) == getson(p) ? fa[p] : p);
}

void access(int p)
{
	for (int pre = 0; p; pre = p, p = fa[p])
	{
		splay(p);
		ch[p][1] = pre;
		Assert(p);
	}
}

void makeroot(int p)
{
	access(p); splay(p); col[p] ^= 1;
}

int find(int p)
{
	access(p); splay(p);
	while (ch[p][0])
		p = ch[p][0];
	return p;
}

void link(int u, int v)
{
	makeroot(u); fa[u] = v;
}

void cut(int u, int v)
{
	makeroot(u); access(v); splay(v);
	if (fa[u] == v && !ch[u][1])
		fa[u] = ch[v][0] = 0;
	Assert(v);
}

int query(int u, int v)
{
	makeroot(u); access(v); splay(v);
	return s[v];
}

void change(int x, int v)
{
	splay(x); a[x] = v;
}


int main()
{
	n = read(); m = read();
	for (int i = 1; i <= n; ++i)
		s[i] = a[i] = read();
	for (int _ = 1; _ <= m; ++_)
	{
		int opt = read(), u = read(), v = read();
		switch (opt)
		{
			case 0:
				writee(query(u, v));
				break;
			case 1:
				if (find(u) != find(v))
					link(u, v);
				break;
			case 2:
				if (find(u) == find(v))
					cut(u, v);
				break;
			case 3:
				change(u, v);
		}
	}
	return 0;
}

(逃

原文