码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1057. Stack (30)

时间:2014-05-08 13:42:29      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   tar   color   

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

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

bubuko.com,布布扣
#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\n");
            else
            {
                printf("%d\n",treeArray.findMedian((s.size()+1)/2));
            }
            break;
        case o:
            if(s.empty())
                printf("Invalid\n");
            else
            {
                key=s.top();
                s.pop();
                printf("%d\n",key);
                treeArray.add(key,-1);
                break;
            }
        }
    }
    return 0;
}
View Code

 

PAT 1057. Stack (30),布布扣,bubuko.com

PAT 1057. Stack (30)

标签:style   blog   class   code   tar   color   

原文地址:http://www.cnblogs.com/wwblog/p/3713963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!