L3-002. 堆栈

时间:2022-01-21 08:23:13

L3-002. 堆栈

题目链接:https://www.patest.cn/contests/gplt/L3-002

线段树

可以用一个数组a[i]维护栈内数字为i的个数,若[0,K]中有n/2个数,即有n/2个比K小的数,则K为中位数。

线段树的数据修改和查询都是O(lgn)的,此题只需维护各个区间内的数的个数即可。

代码如下:

 #include<cstdio>
#include<algorithm>
#include<stack>
#define N 100001
#define lson l,m,n<<1
#define rson m+1,r,n<<1|1
using namespace std;
stack<int>pq;
int st[N<<];
void build(int l,int r,int n,int key);
void change(int l,int r,int n,int key);
void updata(int n);
int query(int l,int r,int n,int key);
int main(void){
freopen("in.txt","r",stdin);
int n,key;
char s[];
scanf("%d",&n);
while(n--){
scanf("%s",s);
switch(s[]){
case 'o':
if(pq.empty())printf("Invalid\n");
else{
key=pq.top();
printf("%d\n",key);
pq.pop();
change(,,,key);
}
break;
case 'u':
scanf("%d",&key);
pq.push(key);
build(,,,key);
break;
case 'e':
if(pq.empty())printf("Invalid\n");
else{
key=pq.size()+;
key>>=;
printf("%d\n",query(,,,key));
}
break;
}
}
return ;
}
void build(int l,int r,int n,int key){
if(l>=r){
st[n]++;
return;
}
int m=(l+r)/;
if(key<=m)build(lson,key);
else build(rson,key);
updata(n);
}
void change(int l,int r,int n,int key){
if(l==r){
st[n]--;
return;
}
int m=(l+r)/;
if(key<=m)change(lson,key);
else change(rson,key);
updata(n);
}
void updata(int n){
st[n]=st[n<<]+st[n<<|];
}
int query(int l,int r,int n,int key){
if(l==r)return l;
int m=(l+r)/;
if(key<=st[n<<])return query(lson,key);
else return query(rson,key-st[n<<]);
}