【捞】求助treapMLE60
查看原帖
【捞】求助treapMLE60
361308
Stinger楼主2021/2/9 11:57

RT,我太菜了

有几个点死递归了

#include <cstdio>
#include <cstdlib>
#include <ctime>

struct Node {
	int ch[2], r, v, cnt, s;
} t[100005];
int tot = 1, p, root = 1;
inline void maintain(const int O) {
	t[O].s = t[t[O].ch[0]].s + t[t[O].ch[1]].s + t[O].cnt;
}

inline void rotate(int& O, const int d) {
	int k(t[O].ch[d ^ 1]);
	t[O].ch[d ^ 1] = t[k].ch[d], t[k].ch[d] = O;
	maintain(O), maintain(k);
	O = k;
}
void insert(int& O, const int x) {// option 1
	if (!O) {O = ++ tot, t[tot].s = t[tot].cnt = 1, t[tot].v = x, t[tot].r = rand(); return;}
	if (t[O].v == x) {++ t[O].cnt, maintain(O); return;}
	int d(t[O].v < x);
	insert(t[O].ch[d], x);
	if (t[t[O].ch[d]].r > t[O].r) rotate(O, d ^ 1);
	maintain(O);
}
void remove(int& O, const int x) {// option 2
	if (t[O].v == x) {
		if (t[O].cnt > 1) {-- t[O].cnt; maintain(O); return;}
		if (t[O].ch[0] || t[O].ch[1]) {
			int d(!t[O].ch[1] || t[t[O].ch[0]].r > t[t[O].ch[1]].r)
			rotate(O, d), remove(t[O].ch[d], x);
			maintain(O);
		}
		else O = 0;
	} else remove(t[O].ch[t[O].v < x], x);
	maintain(O);
}
int rank(const int O, const int x) {// option 3
	if (O == 0) return 0;
	return x < t[O].v ? rank(t[O].ch[0], x) : t[t[O].ch[0]].s + 1 + rank(t[O].ch[1], x);
}
int rank2(const int O, const int x) {// option 4
	if (x <= t[t[O].ch[0]].s) return rank2(t[O].ch[0], x);
	if (x <= t[t[O].ch[0]].s + t[O].cnt) return t[O].v;
	return rank2(t[O].ch[1], x - t[t[O].ch[0]].s - t[O].cnt);
}
void Pre(const int O, const int x) {// option 5
	if (O == 0) return;
	if (t[O].v < x) {
		p = t[O].v;
		Pre(t[O].ch[1], x);
	}
	else Pre(t[O].ch[0], x);
}
void Nxt(const int O, const int x) {// option 6
	if (O == 0) return;
	if (t[O].v > x) {
		p = t[O].v;
		Nxt(t[O].ch[0], x);
	}
	else Nxt(t[O].ch[1], x);
}

int main() {
	srand(time(NULL));
	int n;
	bool mark(0);
	scanf("%d", &n);
	while (n --) {
		int opt, x;
		scanf("%d%d", &opt, &x);
		if (opt == 1) {
			if (mark) insert(root, x);
			else t[1].v = x, t[1].s = t[1].cnt = 1, t[1].r = rand();
			mark = true;
		}
		else if (opt == 2) remove(root, x);
		else if (opt == 3) printf("%d\n", rank(root, x));
		else if (opt == 4) printf("%d\n", rank2(root, x));
		else if (opt == 5) printf("%d\n", (Pre(root, x), p));
		else if (opt == 6) printf("%d\n", (Nxt(root, x), p));
	}
}
2021/2/9 11:57
加载中...