输入样例:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
输出样例:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
这就是套路题。
#include <cstdio>
#include <stack>
using namespace std;
const int N=100000+5;
const int Max=N-5;
int sum[N<<2],ansdex;
stack<int>st;
void update(int n,int val,int l,int r,int pos)
{
if(l==r)
{
sum[pos]+=val;
return;
}
int mid=(l+r)>>1;
if(n<=mid)
update(n,val,l,mid,pos<<1);
else
update(n,val,mid+1,r,pos<<1|1);
sum[pos]=sum[pos<<1]+sum[pos<<1|1];
}
void query(int rank_small,int l,int r,int pos)
{
if(l==r)
{
ansdex=l;
return;
}
int mid=(l+r)>>1;
if(rank_small<=sum[pos<<1])
query(rank_small,l,mid,pos<<1);
else
query(rank_small-sum[pos<<1],mid+1,r,pos<<1|1);
}
char str[20];
int main()
{
int m;scanf("%d",&m);
while(m--)
{
scanf("%s",str);
if(str[1]=='o')
{
if(st.empty())
puts("Invalid");
else
{
printf("%d\n",st.top());
update(st.top(),-1,1,Max,1);
st.pop();
}
}
else if(str[1]=='u')
{
int x;scanf("%d",&x);
update(x,1,1,Max,1);
st.push(x);
}
else
{
if(st.empty())
puts("Invalid");
else
{
int big=st.size();
int rank_small=(big&1)?((big>>1)+1):(big>>1);
query(rank_small,1,Max,1);
printf("%d\n",ansdex);
}
}
}
}