PAT训练(6)

1057. Stack (30)

  首先天真地想到开数组,最差时间复杂度O(n^2),10^10次加运算。较上去三个数据卡时间只拿17分。
  已经想到解决方法,明天再改。


  先贴第一次交的,因为是在30多分钟拿到的17分(这题动键盘之前在纸上写了思路),还不算太差。
  方法:开一个栈处理“Pop”命令和检错,开数组记录各数字出现次数,loger[i]=”数字i的出现次数”;读到”PeekMedian”命令时计算中位数次序,对数组顺序求和定位中位数对应的数组元素。

#include<iostream>
#include<climits>
#include<stack> 
#include<cstring>
using namespace std;

const int maxn=100005;

//线性表+栈 

int PeekMedian(int counter,int *loger)
{
    int x,temp;
    x=(counter%2==0)?counter/2:(counter+1)/2;
    temp=0;
    for(int i=1;;i++)
    {
        temp+=loger[i];
        if(temp>=x)
            return i;
    }
}

int main()
{
    #ifdef ONLINE_JUDGE
    #else
        freopen("G:\\X下载\\PAT\\test_in.txt","r",stdin);
    #endif

    stack<int> sta;
    int n,loger[maxn],curnum,counter;
    string oder;
    while(cin>>n)
    {
        counter=0;
        memset(loger,0,sizeof(loger));
        for(int i=1;i<=n;i++)
        {
            cin>>oder;
            if(oder=="Push")
            {
                cin>>curnum;
                sta.push(curnum);
                loger[curnum]++;
                counter++;
            }
            if(oder=="Pop")
            {
                if(sta.size()==0)
                    printf("Invalid\n");
                else
                {
                    curnum=sta.top();
                    printf("%d\n",curnum);
                    sta.pop();
                    loger[curnum]--;
                    counter--;
                }
            }
            if(oder=="PeekMedian")
            {
                if(sta.size()==0)
                    printf("Invalid\n");
                else
                {
                    printf("%d\n",PeekMedian(counter,loger));
                }
            }
        }
    }
}


明天这里要填上代码!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值