Splay求条
查看原帖
Splay求条
682196
2022dyxwitHLove楼主2024/8/13 15:52
#include <bits/stdc++.h>
using namespace std;
const int N = 1e7 + 5;
const int inf = 0x3f3f3f3f;
int n, idx, rt, y, z, k, l, now;
struct Node{
	int fa;
	int son[2];
	int val;
	int siz;
	int cnt;
}tree[N];
void pushup(int x) {
	tree[x].siz = tree[tree[x].son[0]].siz + tree[tree[x].son[1]].siz + tree[x].cnt;
}
void rotate(int x) {
	int y = tree[x].fa;
	int z = tree[y].fa;
	int k = (tree[y].son[1] == x);
	int l = (tree[z].son[1] == y);
	tree[y].son[k] = tree[x].son[k ^ 1];
	tree[tree[x].son[k ^ 1]].fa = y;
	tree[x].son[k ^ 1] = y;
	tree[y].fa = x;
	tree[z].son[l] = x;
	tree[x].fa = z;
	pushup(y);
	pushup(x);
}
void splay(int x, int o) {
	if (x == o) return;
	while(tree[x].fa != o) {
		if (tree[tree[x].fa].fa != o) {
			if ((tree[tree[x].fa].son[1] == x) ^ (tree[tree[tree[x].fa].fa].son[1] == tree[x].fa)) rotate(x);
			else rotate(tree[x].fa);
		}
		rotate(x);
	}
	if (!o) rt = x;
}
void insert(int x, int fa, int o) {
	if (!x) {
		tree[fa].son[o > tree[fa].val] = ++idx;
		tree[idx].fa = fa;
		tree[idx].val = o;
		tree[idx].cnt = 1;
		tree[idx].siz = 1;
		if (idx == 1) rt = 1;
		now = idx;
		return;
	}
	if (o == tree[x].val) {
		++tree[x].cnt;
		++tree[x].siz;
		now = x;
		return;
	}
	insert(tree[x].son[o > tree[x].val], x, o);
	pushup(x);
}
int kth(int x, int o) {
	if (tree[tree[x].son[0]].siz >= o) {
		return kth(tree[x].son[0], o);
	}
	if (tree[tree[x].son[0]].siz + tree[x].cnt >= o) return now = x;
	return kth(tree[x].son[1], o - tree[tree[x].son[0]].siz - tree[x].cnt);
}
int rk(int x, int o) {
	if (x == 0) return now = 0;
	if (tree[x].val > o) return rk(tree[x].son[0], o);
	if (tree[x].val == o) {
		now = x;
		return tree[tree[x].son[0]].siz + 1; 
	}
	return tree[tree[x].son[0]].siz + tree[x].cnt + rk(tree[x].son[1], o);
}
int pre(int x, int o) {
	if (x == 0) return 0;
	if (tree[x].val >= o) return pre(tree[x].son[0], o);
	now = x;
	return max(tree[x].val, pre(tree[x].son[1], o));
}
int suf(int x, int o) {
	if (x == 0) return inf;
	if (tree[x].val <= o) return suf(tree[x].son[1], o);
	now = x;
	return min(tree[x].val, suf(tree[x].son[0], o));
}
void del(int x) {
	now = 0;
	pre(rt, x);
	splay(now, 0);
	suf(rt, x);
	splay(now, rt);
	if (tree[tree[now].son[0]].cnt == 1) tree[now].son[0] = 0;
	--tree[tree[now].son[0]].cnt;
	--tree[tree[now].son[0]].siz;
	pushup(now);
	pushup(rt);
}
int main() {
	cin >> n;
	insert(rt, 0, inf);
	insert(rt, 0, -inf);
	for (int i = 1, op, x; i <= n; ++i) {
		cin >> op >> x;
		if (op == 1) insert(rt, 0, x);
		if (op == 2) del(x);
		if (op == 3) cout << rk(rt, x) << '\n';
		if (op == 4) cout << tree[kth(rt, x + 1)].val << '\n';
		if (op == 5) cout << pre(rt, x) << '\n';
		if (op == 6) cout << suf(rt, x) << '\n';
		splay(now, 0);
	}
}
2024/8/13 15:52
加载中...