普通平衡树模板全RE求改
查看原帖
普通平衡树模板全RE求改
487843
Xx0okoukio0xX楼主2024/8/9 10:56

题目:题目链接

代码如下:

#include<bits/stdc++.h>
using namespace std;

const int Tree_Size_Max = 1e5 + 10;

int n;
int opt;

struct TREE{
	int siz;
	TREE* left;
	TREE* right;
	int val;
	int ran;
	int count;
	
	TREE operator=(const TREE *tp){
		siz = tp -> siz;
		left = tp -> left;
		right = tp -> right;
		val = tp -> val;
		count = tp -> count;
	}
	
};

TREE* root;
TREE* a,* b,* c;
int x;
int sz;
TREE tree[Tree_Size_Max];

void upd_siz(TREE *x){
	x->siz = x->count;
	if (x->left != nullptr) x->siz += x-> left -> siz;
	if (x->right != nullptr) x->siz += x-> right -> siz;
}

TREE* new_TREE(int x){
	sz++;
	tree[sz].count = 1;
	tree[sz].left = nullptr;
	tree[sz].right = nullptr;
	tree[sz].ran = rand();
	tree[sz].siz = 1;
	tree[sz].val = x;
	return &tree[sz];
}

void split(TREE* now, int k, TREE* x, TREE* y){
	if(now == nullptr){
		x = y = nullptr;
		return;
	}
	if(now -> val <= k){
		x = now;
		split(now -> right, k, now -> right, y);
	}else{
		y = now;
		split(now -> left , k, x, now -> left );
	}
	upd_siz(now);
}

TREE* merge(TREE *x, TREE *y){
	if(x == nullptr && y == nullptr) return nullptr;
	if(x == nullptr) return y;
	if(y == nullptr) return x;
	
	if(x -> ran < y -> ran){
		y -> left = merge(x, y -> left);
		upd_siz(y);
		return y;
	}
	else{
		x -> right = merge(x -> right, y);
		upd_siz(x);
		return x; 
	}
}

void insert(int x){
	a = nullptr;
	b = nullptr;
	split(root, x, a, b);
	root = merge(a, merge(new_TREE(x), b));
}

void del(int x){
	a = nullptr;
	b = nullptr;
	split(root, x, a, b);
	split(a, x-1, a, c);
	c = merge(merge(a, c), b);
	root = merge( merge( a, c), b);
}

void rnk(int x){
	a = nullptr;
	b = nullptr;
	split(root, x-1, a, b);
	printf("%d\n", a -> siz + 1);
	root = merge(a, b);
}

void kth(TREE* now, int k){
	while(1){
		if(now -> left -> siz >= k){
			now = now -> left;
		}else if(now -> left -> siz + 1 == k){
			printf("%d\n", now -> val);
			return;
		}else{
			k -= now -> left -> siz + 1;
			now = now -> right;
		}
	}
}

void pre(int x){
	a = nullptr;
	b = nullptr;
	split(root, x-1, a, b);
	kth(a, a -> siz);
	merge(a, b);
}

void nxt(int x){
	a = nullptr;
	b = nullptr;
	split(root, x, a, b);
	kth(b, 1);
	merge(a, b);
}

int main(){
	srand((unsigned) time (NULL));
	scanf("%d",&n);
	while(n--){
		scanf("%d %d",&opt,&x);
		if(opt==1) insert(x);
		if(opt==2) del(x);
		if(opt==3) rnk(x);
		if(opt==4) kth(root,x);
		if(opt==5) pre(x);
		if(opt==6) nxt(x);
	}
	return 0;
}
2024/8/9 10:56
加载中...