本子君

PAT 甲级 1057 Stack

最近开始写PAT了,20分值的题好多都是STL水过的模拟(STL要再好好看看了,要总结一下几种容器的函数用法,不能用一个查一个啊)

猛然写到这个题,用vector一通乱搞,A了第一个测试点,其它点T了,第一次在PAT上T,很是震惊(A了一个测试点竟然有15分......)

查了一下竟然用到了树状数组,又震惊了一下(PAT甲级有点猛)

 

先上代码,明天更新作法

#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=1e5+10;
stack<int> s;
int tree[maxn];

void update(int x,int k)
{
    if(k==1) {for(;x<=maxn;x+=x & (-x)) tree[x]++;}
    else {for(;x<=maxn;x+=x & (-x)) tree[x]--;}
}

int query(int x)
{
    int ans=0;
    for(;x>0;x-=x & (-x)) ans+=tree[x];
    return ans;
}

int solve()
{
    int l=1,r=maxn,sum=(s.size()+1)/2;
    while(l<r)
    {
        int mid=(l+r)>>1;
        if(query(mid)>=sum) r=mid;
        else l=mid+1;
    }
    return l;
}

int main()
{
    int t; scanf("%d",&t);
    while(t--)
    {
        string str; cin>>str;
        if(str[1]=='o')
        {
            if(s.size()==0) printf("Invalid\n");
            else {int temp=s.top(); printf("%d\n",temp); update(temp,2); s.pop();}
        }
        else if(str[1]=='u')
        {
            int num;
            scanf("%d",&num); s.push(num); update(num,1);
        }
        else
        {
            if(s.size()==0) printf("Invalid\n");
            else printf("%d\n",solve());
        }
    }
    return 0;
}

 

posted on 2019-10-07 01:10  本子君  阅读(196)  评论(0编辑  收藏  举报

导航