Treap 模板代码

struct Node {
	int pri, data, num, sz, ch[2], fa;
}t[maxn];

int pos;

struct Treap {
	int root;
	int newNode(int x) {
		t[++ pos] = (Node){rand(), x, 1, 1, 0, 0, 0};
		return pos;
	}
	void update(int x) {
		t[x].sz = t[t[x].ch[0]].sz + t[t[x].ch[1]].sz + t[x].num;
	}
	int locate(int x) {
		return x == t[t[x].fa].ch[1];
	}
	void rotate(int x){
		int y = t[x].fa, z = t[y].fa, p = locate(x);
		t[y].ch[p] = t[x].ch[p ^ 1], t[x].ch[p ^ 1] = y, t[t[y].ch[p]].fa = y;
		t[x].fa = t[y].fa, t[y].fa = x;
		update(y), update(x);
		if (z) {
			t[z].ch[t[z].ch[1] == y] = x;
			update(z);
		}
	}
	void maintain(int x) {
		while (x) {
			update(x);
			x = t[x].fa;
		}
	}
	void insert(int data) {
		if (root == 0) {
			root = newNode(data);
			return ;
		}
		int x = root;
		while (true) {
			if (t[x].data == data){
				t[x].num ++;
				break;
			}
			int p = data > t[x].data;
			if (!t[x].ch[p]) {
				t[x].ch[p] = newNode(data);
				t[t[x].ch[p]].fa = x;
				x = t[x].ch[p];
				break;
			}
			x = t[x].ch[p];
		}
		maintain(x);
		while (t[x].fa && t[t[x].fa].pri < t[x].pri)
			rotate(x);
		if (t[x].fa == 0)
			root = x;
	}
	int get_pos(int data) {
		int x = root;
		while (true) {
			if (t[x].data == data)
				return x;
			int p = data > t[x].data;
			x = t[x].ch[p];
		}
		return x;
	}
	void del(int data) {
		int x = get_pos(data);
		if (t[x].num > 1){
			t[x].num --;
			maintain(x);
			return ;
		}
		while (t[x].ch[0] + t[x].ch[1]) {
			int p = t[t[x].ch[1]].pri > t[t[x].ch[0]].pri;
			rotate(t[x].ch[p]);
			if (t[t[x].fa].fa == 0)
				root = t[x].fa;
		}
		t[x].num = 0;
		maintain(x);
		t[t[x].fa].ch[locate(x)] = 0;
		t[x].fa = 0;
		if (root == x)
			root = 0;
	}
	int rks(int data) {
		int x = root;
		int res = 0;
		while (true) {
			if (t[x].data == data)
				return res + t[t[x].ch[0]].sz + 1;
			if (t[x].data < data)
				res += t[x].num + t[t[x].ch[0]].sz;
			x = t[x].ch[(data > t[x].data)];
		}
	}
	int kth(int k) {
		int x = root;
		while (x) {
			if (t[t[x].ch[0]].sz >= k)
				x = t[x].ch[0];
			else if (t[x].num + t[t[x].ch[0]].sz >= k)
				return t[x].data;
			else k -= t[x].num + t[t[x].ch[0]].sz, x = t[x].ch[1];
		}
	}
	int pre(int data) {
		int x = root, ans;
		while (x) {
			if (t[x].data < data)
				ans = t[x].data, x = t[x].ch[1];
			else x = t[x].ch[0];
		}
		return ans;
	}
	int suf(int data) {
		int x = root, ans;
		while (x) {
			if (t[x].data > data)
				ans = t[x].data, x = t[x].ch[0];
			else x = t[x].ch[1];
		}
		return ans;
	}
}treap;

作者:DE_aemmprty

出处:https://www.cnblogs.com/aemmprty/p/17469855.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   DE_aemmprty  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示