zoukankan      html  css  js  c++  java
  • PAT 1057. Stack (30)

    题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1057

    用树状数组和二分搜索解决,对于这种对时间复杂度要求高的题目,用C的输入输出显然更好

    #include <cstdio>
    #include <string>
    #include <vector>
    #include <stack>
    using namespace std;
    
    const int NUM=100001;
    
    struct TreeArray
    {
        vector<int> cStore;
        TreeArray()
        {
            cStore=vector<int>(NUM,0);
        }
        int lowerBit(int x)
        {
            return x&(-x);
        }
        void add(int location,int addedValue)
        {
            while(location<=NUM)
            {
                cStore[location]+=addedValue;
                location+=lowerBit(location);
            }
        }
        int getSum(int location)
        {
            int sum(0);
            while(location>0)
            {
                sum+=cStore[location];
                location-=lowerBit(location);
            }
            return sum;
        }
    
        int findMedian(int toFind,int low=1,int high=NUM)
        {
            if(low==high)
                return low;
            int median=(low+high)>>1;
            if(getSum(median)<toFind)
            {
                return findMedian(toFind,median+1,high);
            }
            else
            {
                return findMedian(toFind,low,median);
            }
        }
    };
    
    TreeArray treeArray;
    stack<int> s;
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int N;
        scanf("%d",&N);
        char command[20];
        int key;
        for(int i=0;i<N;++i)
        {
            scanf("%s",command);
            switch(command[1])
            {
            case 'u':
                scanf("%d",&key);
                s.push(key);
                treeArray.add(key,1);
                break;
            case 'e':
                if(s.empty())
                    printf("Invalid
    ");
                else
                {
                    printf("%d
    ",treeArray.findMedian((s.size()+1)/2));
                }
                break;
            case 'o':
                if(s.empty())
                    printf("Invalid
    ");
                else
                {
                    key=s.top();
                    s.pop();
                    printf("%d
    ",key);
                    treeArray.add(key,-1);
                    break;
                }
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    shell学习(11)- seq
    bash快捷键光标移动到行首行尾等
    shell学习(10)- if的使用
    Python 执行 Shell 命令
    查看 jar 包加载顺序
    Linux 中的 sudoers
    Ubuntu 开机启动程序
    指定 Docker 和 K8S 的命令以及用户
    Spark on K8S(Standalone)
    Spark on K8S (Kubernetes Native)
  • 原文地址:https://www.cnblogs.com/wwblog/p/3713963.html
Copyright © 2011-2022 走看看