Luogu3871 [TJOI2010]中位数 (平衡树)

"#define int long long" 导致100pts ( ightarrow) 80pts

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("

----------

")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 100007;

struct Treap{
	int ch[2], fa, val, siz, tot;
}t[N << 2];
int root, treeIndex;
inline void Pushup(int rt){
	t[rt].siz = t[t[rt].ch[0]].siz + t[t[rt].ch[1]].siz + t[rt].tot;
}
inline int Ident(int x){
	return t[t[x].fa].ch[1] == x;
}
inline void Rotate(int x){
	int y = t[x].fa, z = t[y].fa, k = Ident(x);
	t[z].ch[Ident(y)] = x, t[x].fa = z;
	t[y].ch[k] = t[x].ch[k ^ 1], t[t[x].ch[k ^ 1]].fa = y;
	t[x].ch[k ^ 1] = y, t[y].fa = x;
	Pushup(y), Pushup(x);
}
inline void Splay(int x, int pos){
	while(t[x].fa != pos){
		int y = t[x].fa, z = t[y].fa;
		if(z != pos){
			Ident(x) == Ident(y) ? Rotate(y) : Rotate(x);
		}
		Rotate(x);
	}
	if(!pos) root = x;
}
inline void Insert(int x){
	int u = root, fa = 0;
	while(u && t[u].val != x){
		fa = u;
		u = t[u].ch[x > t[u].val];
	}
	if(u){
		++t[u].tot;
	}
	else{
		u = ++treeIndex;
		t[u].val = x;
		t[u].fa =fa;
		t[u].ch[0] = t[u].ch[1] = 0;
		t[u].siz = t[u].tot = 1;
		if(fa) t[fa].ch[x > t[fa].val] = u; // !
	}
	Splay(u, 0);
}
inline int Kth(int x){
	int u = root;
	if(t[u].siz < x) return 0;
	while(1){
		int v = t[u].ch[1];
		if(t[v].siz + t[u].tot < x){
			x -= t[v].siz + t[u].tot;
			u = t[u].ch[0]; // !
		}
		else if(t[v].siz >= x){
			u = v;
		}
		else{
			return t[u].val;
		}
	}
}
int main(){
	int n;
	io >> n;
	Insert(2147483647);
	Insert(-2147483647);
	R(i,1,n){
		int x;
		io >> x;
		Insert(x);
	}
	int m;
	io >> m;
	while(m--){
		char str[7];
		scanf("%s", str + 1);
		if(str[1] == 'a'){
			int x;
			io >> x;
			Insert(x);
			++n;
		}
		else{
			if(n & 1){
				printf("%d
", Kth(((n + 1) >> 1) + 1));
			}
			else{
				int ans1 = Kth((n >> 1) + 1);
				int ans2 = Kth(((n + 2) >> 1) + 1);
				printf("%d
", Min(ans1, ans2));
			}
		}
	}
	
	return 0;
}

原文地址:https://www.cnblogs.com/bingoyes/p/11264303.html