1057 Stack (30 分)
阿新 • • 發佈:2018-11-24
題目 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");
}
}
}