PAT L3-002. 堆栈

树状数组,二分。

一堆数字,可以删除栈顶,压入数字,求中位数,可以线段树,也可以树状数组上二分。

#include<map>
#include<set>
#include<ctime>
#include<cmath>
#include<queue>
#include<string>
#include<stack>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;

stack<int>S;
int n; char op[50];

int c[100010];

int lowbit(int x)
{
    return x&(-x);
}

int get(int p)
{
    int res=0;
    while(p>0)
    {
        res=res+c[p];
        p=p-lowbit(p);
    }
    return res;
}

void update(int p,int val)
{
    while(p<=100000)
    {
        c[p]=c[p]+val;
        p=p+lowbit(p);
    }
}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%s",op);
        if(strcmp(op,"Pop")==0)
        {
            if(S.empty()) printf("Invalid
");
            else
            {
                printf("%d
",S.top());
                update(S.top(),-1); S.pop();
            }
        }
        else if(strcmp(op,"Push")==0)
        {
            int x; scanf("%d",&x);
            S.push(x);
            update(x,1);
        }
        else
        {
            if(S.size()==0)
            {
                printf("Invalid
");
                continue;
            }
            int limit = (S.size()+1)/2;
            int L=1,R=100000,p=-1;

            while(L<=R)
            {
                int mid = (L+R)/2;
                if(get(mid)>=limit) p=mid,R=mid-1;
                else L=mid+1;
            }

            printf("%d
",p);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/6600452.html