社区讨论

100pts求调

P5076【深基16.例7】普通二叉树(简化版)参与者 1已保存回复 3

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
3 条
当前快照
1 份
快照标识符
@mhj2vyhk
此快照首次捕获于
2025/11/03 19:50
4 个月前
此快照最后确认于
2025/11/03 19:50
4 个月前
查看原帖
CPP
#include <iostream>
#define MAXN 100010
int n , root , cnt , opt , num , x;
struct node {
	int left , right , size , value , num;
	node(int l , int r , int s , int v)
		: left(l) , right(r) , size(s) , value(v) , num(1) {}
	node() {}
}t[MAXN];
inline void update(int root) {
	t[root].size = t[t[root].left].size + t[t[root].right].size + t[root].num;
}
int ank(int x , int root) {
	if (root) {
		if (x < t[root].value) return ank(x , t[root].left);
		if (x > t[root].value) return ank(x , t[root].right) + t[t[root].left].size + t[root].num;
		return t[t[root].left].size + t[root].num;
	}
	return 1;
}
int kth(int x , int root) {
	if (x <= t[t[root].left].size) return kth(x , t[root].left);
	if (x <= t[t[root].left].size + t[root].num) return t[root].value;
	return kth(x - t[t[root].left].size - t[root].num , t[root].right);
}
void insert(int x , int& root) {
	if (x < t[root].value) {
		if (!t[root].left) t[t[root].left = ++cnt] = node(0 , 0 , 1 , x);
		else insert(x , t[root].left);
	} else if (x > t[root].value) {
		if (!t[root].right) t[t[root].right = ++cnt] = node(0 , 0 , 1 , x);
		else insert(x , t[root].right);
	} else {
		t[root].num++;
	}
	update(root);
}
int main() {
	scanf("%d" , &n);
	t[root = ++cnt] = node(0 , 0 , 1 , 2147483647);
	while (n--) {
		scanf("%d%d" , &opt , &x);
		num++;
		if (opt == 1) printf("%d\n" , ank(x , root));
		else if (opt == 2) printf("%d\n" , kth(x , root));
		else if (opt == 3) printf("%d\n" , kth(ank(x , root) - 1 , root));
		else if (opt == 4) printf("%d\n" , kth(ank(x + 1 , root) , root));
		else num-- , insert(x , root);
	}
	return 0;
}
大多为《深入浅出程序设计竞赛(基础篇)》代码。

回复

3 条回复,欢迎继续交流。

正在加载回复...