FHQTreap

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;


inline int read(int& x) {
	char ch = getchar();
	int f = 1; x = 0;
	while (ch > '9' || ch < '0') { if (ch == '-')f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); }
	return x * f;
}
//void ReadFile() {
//	FILE* stream1;
//	freopen_s(&stream1,"in.txt", "r", stdin);
//	freopen_s(&stream1,"out.txt", "w", stdout);
//}

static auto speedup = []() {ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }();

#define lson(x) tr[x].l
#define rson(x) tr[x].r

const int maxn = 1e5 + 7;
std::mt19937 rnd(233);

struct Node {
	int l, r, key;
	int nRand;
	int size;
}tr[maxn];

int idx = 0,root = 0;
int getNode(int k) {
	tr[++idx].key = k;
	tr[idx].nRand = rnd();
	tr[idx].size = 1;
	return idx;
}

void update(int f) {
	tr[f].size = tr[lson(f)].size + tr[rson(f)].size + 1;
}

void split(int p,int k,int &x,int &y) {
	if (!p) x = y = 0;
	else {
		if (tr[p].key <= k) {
			x = p;
			split(rson(p), k, rson(p), y);
		}
		else {
			y = p;
			split(lson(p), k, x, lson(p));
		}
		update(p);
	}
}

int merge(int x, int y) {
	if (!x || !y) return x + y;
	if (tr[x].nRand > tr[y].nRand) {
		rson(x) = merge(rson(x),y);
		update(x);
		return x;
	}
	else {
		lson(y) = merge(x, lson(y));
		update(y);
		return y;
	}
}

void insert(int k) {
	int x, y;
	split(root,k,x,y);
	root = merge(merge(x, getNode(k)), y);
}
void del(int k) {
	int x, y, z;
	split(root, k, x, y);
	split(x, k - 1, x, z);
	z = merge(lson(z),rson(z));
	root = merge(merge(x,z),y);
}

int getRank(int k) {
	int x, y;
	split(root, k - 1, x, y);
	int ans = tr[x].size + 1;
	root = merge(x, y);
	return ans;
}

int getKth(int rank) {
	int cur = root;
	while (cur) {
		if (tr[lson(cur)].size + 1 == rank) break;
		else if (tr[lson(cur)].size >= rank) {
			cur = lson(cur);
		}
		else {
			rank -= tr[lson(cur)].size + 1;
			cur = rson(cur);
		}
	}
	return tr[cur].key;
}

int getPre(int k) {
	int x, y;
	split(root, k - 1, x, y);
	int cur = x;
	while (rson(cur)) cur = rson(cur);
	int ans = tr[cur].key;
	root = merge(x, y);
	return ans;
}

int getNext(int k) {
	int x, y;
	split(root, k, x, y);
	int cur = y;
	while (lson(cur)) cur = lson(cur);
	int ans = tr[cur].key;
	root = merge(x, y);
	return ans;
}

int n;
int main()
{
	cin >> n;

	int a, b;
	for (int i = 1; i <= n; i++) {
		cin >> a >> b;
		switch (a)
		{
		case 1:insert(b); break;
		case 2:del(b); break;
		case 3:cout << getRank(b) << endl;  break;
		case 4:
		{
			cout << getKth(b) << endl;
			break;
		}
		case 5:
		{
			cout << getPre(b) << endl;
			break;
		}
		case 6:
		{
			cout << getNext(b) << endl;
			break;
		}
		default:
			break;
		}
	}
	return 0;
}

你可能感兴趣的:(树论,c++)