锰锌求助BST(马蜂良好)
查看原帖
锰锌求助BST(马蜂良好)
537520
DESTRUCTION_3_2_1楼主2023/2/3 16:32
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int INF = 2147483647;
const int SZ = 1e4 + 5;
struct Binary_Search_Tree {
	int val, siz, count;
	int lc, rc;
	Binary_Search_Tree (int val_, int siz_, int count_, int lc_, int rc_) 
		: val(val_), siz(siz_), count(count_), lc(lc_), rc(rc_) {};
	Binary_Search_Tree () {}
}tr[SZ];
int m, opt, x, n, root;
void insert (int &o, int x) {
	if (x == tr[o].val) {
		tr[o].count++;
		return;
	}
	if (x < tr[o].val)
		if (!tr[o].lc) tr[tr[o].lc = ++n] = Binary_Search_Tree(x, 1, 1, 0, 0);
		else insert(tr[o].lc, x);
	if (x > tr[o].val)
		if (!tr[o].rc) tr[tr[o].rc = ++n] = Binary_Search_Tree(x, 1, 1, 0, 0);
		else insert(tr[o].rc, x);
	tr[o].siz = tr[tr[o].lc].siz + tr[tr[o].rc].siz + tr[o].count;
}
int rank (int o, int x) {
	if (!o) return -INF;
	if (x == tr[o].val) return tr[tr[o].lc].siz;
	if (x < tr[o].val) return rank(tr[o].lc, x);
	if (x > tr[o].val) return rank(tr[o].rc, x) + tr[tr[o].lc].siz + tr[o].count;
}
int kth (int o, int x) {
	if (!o) return INF;
	if (x <= tr[tr[o].lc].siz) return kth(tr[o].lc, x);
	if (x <= tr[tr[o].lc].siz + tr[o].count) return tr[o].val;
	return kth(tr[o].rc, x - tr[tr[o].lc].siz - tr[o].count);
}
signed main(void)
{
	cin >> m;
	while (m--) {
		cin >> opt >> x;
		if (opt == 1) cout << rank(root, x) << endl;
		if (opt == 2) cout << kth(root, x) << endl;
		if (opt == 3) cout << kth(root, rank(root, x) - 1) << endl;
		if (opt == 4) cout << kth(root, rank(root, x + 1)) << endl;
		if (opt == 5) 
			if (n) insert(root, x);
			else tr[++n] = Binary_Search_Tree(x, 1, 1, 0, 0);
	}
	return 0;
}

蒟蒻 BSTBST 板子调了一天没敲过

2023/2/3 16:32
加载中...