虽 A 不懂,求助 Splay,玄关
查看原帖
虽 A 不懂,求助 Splay,玄关
712506
Lucky_Cloud楼主2024/4/12 16:44
#include <bits/stdc++.h>
using namespace std;

int read() {
	int res = 0, f = 1; char c = getchar();
	while (c > '9' || c < '0') {
		if (c == '-') f = -1;
		c = getchar();
	}
	while (c >= '0' && c <= '9') {
		res = (res << 1) + (res << 3) + (c ^ 48);
		c = getchar();
	}
	return f == 1 ? res : -res;
}

const int N = 1e6 + 5;
int root, tot, n;
struct tree {
	int siz;
	int ch[2];
	int fa;
	int dat;
	int cnt;
} t[N];

void updsiz(int x) {
	int ls = t[x].ch[0], rs = t[x].ch[1];
	t[x].siz = t[ls].siz + t[rs].siz + t[x].cnt;
}

void rotate(int x) {
	int y = t[x].fa;
	int z = t[y].fa;
	int k = (t[y].ch[1] == x);
	t[z].ch[y == t[z].ch[1]] = x;
	t[x].fa = z;
	t[y].ch[k] = t[x].ch[k ^ 1];
	t[t[x].ch[k ^ 1]].fa = y;
	t[y].fa = x;
	t[x].ch[k ^ 1] = y;
	updsiz(x), updsiz(y);
}

void splay(int x, int goal) {
	while (t[x].fa != goal) {
		int y = t[x].fa, z = t[y].fa;
		if (z != goal) 
			(t[z].ch[0] == y) ^ (t[y].ch[0] == x) ? rotate(x) : rotate(y);
		rotate(x);
	}
	if (goal == 0) root = x;
}

void find(int x) {
	int u = root;
	if (!u) return ;
	while (t[u].ch[x > t[u].dat] && x != t[u].dat) 
		u = t[u].ch[x > t[u].dat];
	splay(u, 0);
}

void ins(int x) {
	int u = root, fa = 0;
	while (u && t[u].dat != x) {
		fa = u;
		u = t[u].ch[t[u].dat < x];
	}
	if (u) t[u].cnt++;
	else {
		u = ++tot;
		if (fa)
			t[fa].ch[x > t[fa].dat] = u;
		t[u].ch[0] = t[u].ch[1] = 0;
		t[u].fa = fa;
		t[u].dat = x;
		t[u].siz = t[u].cnt = 1;
	}
	splay(u, 0);
}

int Next(int x, int f) {
	find(x);
	int u = root;
	if (t[u].dat > x && f) return u;
	if (t[u].dat < x && !f) return u;
	u = t[u].ch[f];
	while (t[u].ch[f ^ 1]) u = t[u].ch[f ^ 1];
	return u;
}

void del(int x) {
	int lst = Next(x, 0);
	int nxt = Next(x, 1);
	splay(lst, 0);
	splay(nxt, lst);
	int del = t[nxt].ch[0];
	if (t[del].cnt > 1) {
		t[del].cnt--;
		splay(del, 0);
	} else t[nxt].ch[0] = 0;
	splay(nxt, 0);
}

int Kth(int x) {
	int u = root;
	if (t[u].siz < x) return 0;
	while (1) {
		int y = t[u].ch[0];
		if (x > t[y].siz + t[u].cnt) {
			x -= t[y].siz + t[u].cnt;
			u = t[u].ch[1];
		}
		else if (t[y].siz >= x)
			u = y;
		else return t[u].dat;
	}
}

int main() {
	n = read();
	ins(1e9);
	ins(-1e9);
	while (n--) {
		int op = read(), x = read();
		if (op == 1) ins(x);
		if (op == 2) del(x);
		if (op == 3) {
			find(x);
			cout << t[t[root].ch[0]].siz << '\n';
		}
		if (op == 4) 
			cout << Kth(x + 1) << '\n';
		if (op == 5) 
			cout << t[Next(x, 0)].dat << '\n';
		if (op == 6) 
			cout << t[Next(x, 1)].dat << '\n';
	}
	return 0;
}

附数据:

5
1 24
1 25
1 20
3 23
3 23
2
2

主要问题在于 find。怎样去写 find

2024/4/12 16:44
加载中...