PAT (Advanced Level) 1057. Stack (30)

时间:2023-03-10 01:18:51
PAT (Advanced Level) 1057. Stack (30)

树状数组+二分。

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<stack>
#include<vector>
using namespace std; const int maxn=+;
int n;
int c[maxn];
stack<int>S; int lowbit(int x){
return x&(-x);
} int getsum(int pos)
{
int res=;
while(pos>)
{
res=res+c[pos];
pos=pos-lowbit(pos);
}
return res;
} void update(int pos,int val)
{
while(pos<=)
{
c[pos]=c[pos]+val;
pos=pos+lowbit(pos);
}
} int main()
{
while(!S.empty()) S.pop();
memset(c,,sizeof c);
scanf("%d",&n);
int sz=;
for(int i=;i<=n;i++)
{
char op[]; scanf("%s",op);
if(strcmp(op,"Pop")==)
{
if(sz==) printf("Invalid\n");
else
{
sz--;
printf("%d\n",S.top());
update(S.top(),-);
S.pop();
}
}
else if(strcmp(op,"PeekMedian")==)
{
if(sz==) printf("Invalid\n");
else
{
int l=,r=;
int ans;
while(l<=r)
{
int mid=(l+r)/;
if(getsum(mid)>=(sz+)/)
{
ans=mid;
r=mid-;
}
else l=mid+;
}
printf("%d\n",ans);
}
}
else
{
int num; scanf("%d",&num);
update(num,);
sz++;
S.push(num);
}
}
return ;
}