fhq treap MLE + WA
查看原帖
fhq treap MLE + WA
119533
noctua楼主2021/3/13 16:22
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e5 + 5;

int cnt = 0;
int root;
int n;

struct Node {
	int size, val, cv;
	int ch[2]; // ch[0]: lson	ch[1]: rson
};

Node treap[MAXN];

void update(int idx) {
	treap[idx].size = treap[treap[idx].ch[0]].size + treap[treap[idx].ch[1]].size + 1;
}

int newNode(int x) {
	cnt++;
	treap[cnt].size = 1;
	treap[cnt].val = x;
	treap[cnt].cv = (rand() << 15 | rand());
	return cnt;
}

void split(int idx, int k, int &x, int &y) {
	if (!idx) {
		x = y = 0;
		return ;
	}
	if (treap[idx].val <= k) {
		x = idx;
		split(treap[idx].ch[1], k, treap[idx].ch[1], y);
	} else {
		y = idx;
		split(treap[idx].ch[0], k, x, treap[idx].ch[0]);
	}
	update(idx);
}

int merge(int x, int y) { // x
	if (!x || !y) {
		return x + y;
	}
	if (treap[x].cv < treap[y].cv) {
		treap[x].ch[1] = merge(treap[x].ch[1], y);
		update(x);
		return x;
	} else {
		treap[x].ch[0] = merge(x, treap[y].ch[1]);
		update(y);
		return y;
	}
}

void insert(int a) { // insert node a
	int x, y;
	split(root, a, x, y);
	root = merge(merge(x, newNode(a)), y);
}

void del(int a) { // del node a
	int x, y, z;
	split(root, a, x, z);
	split(x, a - 1, x, y);
	y = merge(treap[y].ch[0], treap[y].ch[1]);
	root = merge(merge(x, y), z);
}

int rnk(int a) { // get node a's rank (rank: (the number of nodes that have a value that's less than a) + 1)
	int x, y, res;
	split(root, a - 1, x, y);
	res = treap[x].size + 1;
	root = merge(x, y);
	return res;
}

int kth(int idx, int k) { // get the id of the node that ranks k in the treap
	if (k <= treap[treap[idx].ch[0]].size) {
		kth(treap[idx].ch[0], k);
	} else if (k == treap[treap[idx].ch[0]].size + 1) {
		return idx;
	} else {
		kth(treap[idx].ch[1], k - treap[treap[idx].ch[0]].size - 1);
	}
}

int pre(int a) { // get the precursor node of a (the biggest node that is less than a)
    int x, y, res;
	split(root, a - 1, x, y);
    res = treap[kth(x, treap[x].size)].val;
    root = merge(x, y);
    return res;
}

int pos(int a) { // get the successor node of a (the smallest node that is bigger than a)
    int x, y, res;
    split(root, a - 1, x, y);
    res = treap[kth(y, 1)].val;
    root = merge(x, y);
    return res;
}

int main() {
	srand(time(0));
	cin >> n;
	for (int i = 1; i <= n; i++) {
		int op, a;
		cin >> op >> a;
		switch (op) {
			case 1: insert(a); break;
			case 2: del(a); break;
			case 3: cout << rnk(a) << endl; break;
			case 4: cout << treap[kth(root, a)].val << endl; break;
			case 5: cout << pre(a) << endl; break;
			case 6: cout << pos(a) << endl; break;
				
		}
	}
	return 0;
}
2021/3/13 16:22
加载中...