题目 Advanced Pat
思路 树状数组 比较难
看了很久才看懂,建议不会树状数组的可以去看一下这个大神的博客
https://blog.csdn.net/flushhip/article/details/79165701
讲的很清楚,很明白
然后 参考这个大神的解释
https://blog.csdn.net/SeasonJoe/article/details/80398898?utm_source=blogxgwz3
AC代码
#include <bits/stdc++.h>
const int maxn=100005;
using namespace std;
stack<int> s;//栈只用来操作pop和push
int c[maxn];//c才是用来peekmedian的
int lowbit(int x)
{
return x&(-x);
}
int getsum(int x)
{
int sum=0;
for(int i=x;i>0;i-=lowbit(i))
sum+=c[i];
return sum;
}
void update(int x,int val)
{
for(int i=x;i<=maxn;i+=lowbit(i))
{
c[i]+=val;
}
}
void PeekMedian()
{
int l=1,r=maxn,mid,k=(s.size()+1)/2;
while(l<r)
{
mid=(l+r)/2;
if(getsum(mid)>=k)
r=mid;
else
l=mid+1;
}
printf("%d\n", l);
}
int main()
{
int n;
scanf("%d",&n);
char cmd[15];
for(int i=0;i<n;i++)
{
scanf("%s",cmd);
if(cmd[1]=='u')
{
int t;
scanf("%d",&t);
s.push(t);
update(t,1);
}
else if(cmd[1]=='o')
{
if(!s.empty())
{
int temp=s.top();
printf("%d\n", temp);
s.pop();
update(temp,-1);
}
else
printf("Invalid\n");
}
else
{
if(!s.empty())
PeekMedian();
else
printf("Invalid\n");
}
}
}