关于使用平衡树动态求解中位数
当然stl set<int>也可以
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
const int N=2e4;
struct node
{
node *lf=NULL,*rt=NULL;
const int rawk=rand();
int date,siz=1,cnt=1;
node(const int x){date=x;}
};
struct treap
{
protected:
node *root=NULL;
inline void pu(node *cur){
if(cur==NULL){return;}
int temp=cur->cnt;
temp+=cur->lf==NULL? 0: cur->lf->siz;
temp+=cur->rt==NULL? 0: cur->rt->siz;
cur->siz=temp;
}
void zig(node *&cur){
if(cur==NULL){return;}
node *temp=cur->lf;
cur->lf=temp->rt;
temp->rt=cur;
pu(cur),pu(temp);
cur=temp;
}
void zag(node *&cur){
if(cur==NULL){return;}
node *temp=cur->rt;
cur->rt=temp->lf;
temp->lf=cur;
pu(cur),pu(temp);
cur=temp;
}
void insert_sx(node *&cur,int x){
if(cur==NULL){cur=new node(x);return;}
if(cur->date>x){
insert_sx(cur->lf,x);
if(cur->rawk>cur->lf->rawk){zig(cur);}
}
else if(cur->date<x){
insert_sx(cur->rt,x);
if(cur->rawk>cur->rt->rawk){zag(cur);}
}
else{++cur->cnt;}
pu(cur);
}
node *rankval_sx(node *cur,int rk){
int temp=cur->lf==NULL? 0:cur->lf->siz;
if(rk<=temp){return rankval_sx(cur->lf,rk);}
if(rk<=temp+cur->cnt){return cur;}
return rankval_sx(cur->rt,rk-temp-cur->cnt);
}
public:
void insert(int x){insert_sx(root,x);}
node *rankval(int rk){return rankval_sx(root,rk);}
}t;
int n,G,now;
char cz[10];
int main()
{
scanf("%d",&now);G=now;
--now;
while(G--)
{
scanf("%d",&n);
t.insert(n);
}
scanf("%d",&G);
while(G--)
{
scanf("%s",cz);
if(strcmp(cz,"add")==0)
{scanf("%d",&n);t.insert(n);now++;}
else
{printf("%d\n",t.rankval((now/2)+1)->date);}
}
return 0;
}