#include <bits/stdc++.h>
using namespace std;
#define maxn 100005
#define lson l,m,level*2
#define rson m+1,r,level*2+1
int tree[100010*5];
void update(int l,int r,int level,int x,int b)
{
if(l==r&&x==l)
{
if(b==0)
tree[level]--;
else
tree[level]++;
return ;
}
int m = (l+r)>>1;
if(x<=m)
{
update(lson,x,b);
}
else
{
update(rson,x,b);
}
tree[level] = tree[level*2+1] + tree[level*2];
}
void find(int l, int r, int level , int x)
{
if( l == r && x <= tree[level] )
{
printf("%d\n",l);
return ;
}
int m = (l+r)>>1;
if( tree[level*2] >= x )
{
find( lson,x );
}
else find(rson,(x-tree[level*2]));
}
int main()
{
int N;
scanf("%d",&N);
stack<int>s;
getchar();
int mmax = 100002;
memset(tree,0,sizeof(tree));
while(N--)
{
char c[30];
int num;
scanf("%s",c);
if(!strcmp(c,"Pop"))
{
if(!s.empty())
{
printf("%d\n",s.top());
update(1,mmax,1,s.top(),0);
s.pop();
}
else
{
printf("Invalid\n");
}
}
else if(!strcmp(c,"PeekMedian"))
{
int n = s.size();
if(n>0)
{
if(n%2==1) //注意奇偶数
{
n++;
}
find(1,mmax,1,n/2);
}
else
{
printf("Invalid\n");
}
}
else if(!strcmp(c,"Push"))
{
scanf("%d",&num);
s.push(num);
if(mmax<num) //这里mmax会出错(应该是线段树的N是确定的,而不是不确定的,memory)
{
mmax = num;
}
update(1,mmax,1,num,1);
}
}
}
线段树第k中值
最新推荐文章于 2022-06-24 09:29:13 发布