zoukankan      html  css  js  c++  java
  • 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
    ");
                else {int temp=s.top(); printf("%d
    ",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
    ");
                else printf("%d
    ",solve());
            }
        }
        return 0;
    }
  • 相关阅读:
    代理模式
    组合模式
    yum配置文件详解
    责任链模式
    git看不到别人创建的远程分支
    学习gulpfile.babel.js随笔
    遍历数组的方法
    解决Error: ENOENT: no such file or directory, scandir 安装node-sass报错
    window对象
    Moment.js的一些用法
  • 原文地址:https://www.cnblogs.com/benzikun/p/11629170.html
Copyright © 2011-2022 走看看