zoukankan      html  css  js  c++  java
  • POJ 1442 Black Box -优先队列

    优先队列。。刚开始用蠢办法,经过一个vector容器中转,这么一来一回这么多趟,肯定超时啊。

    超时代码如下:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <cstdlib>
    #include <string>
    #include <vector>
    #include <map>
    #include <queue>
    #include <functional>
    using namespace std;
    #define N 30003
    
    priority_queue<int,vector<int>,greater<int> > que;
    int A[N];
    vector<int> tmp;
    
    int main()
    {
        int m,n,i,j,th,u,k,h;
        while(scanf("%d%d",&m,&n)!=EOF)
        {
            th = 0;
            for(i=0;i<m;i++)
                scanf("%d",&A[i]);
            j = 0;
            k = 0;
            for(i=0;i<n;i++)
            {
                scanf("%d",&u);
                while(j<u)
                {
                    que.push(A[k++]);
                    j++;
                }
                th++;
                for(h=1;h<th;h++)
                {
                    tmp.push_back(que.top());
                    que.pop();
                }
                printf("%d
    ",que.top());
                for(h=0;h<tmp.size();h++)
                    que.push(tmp[h]);
                tmp.clear();
            }
        }
        return 0;
    }
    View Code

    后来看了网上某位大牛的,说是用两个优先队列,一个从大到小的,一个从小到大的,元素在这两个中间中转,可以大大缩短时间。

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <string>
    #include <vector>
    #include <map>
    #include <queue>
    #include <functional>
    using namespace std;
    #define N 30003
    
    priority_queue<int,vector<int>,greater<int> > StoBig;  //从小到大排,先出小的
    priority_queue<int,vector<int>,less<int> > BtoSmall;    //从大到小排,先出大的
    int A[N];
    
    int main()
    {
        int m,n,i,j,th,u,k,h;
        while(scanf("%d%d",&m,&n)!=EOF)
        {
            th = 0;
            for(i=0;i<m;i++)
                scanf("%d",&A[i]);
            j = 0;
            for(i=0;i<n;i++)
            {
                scanf("%d",&u);
                while(j<u)
                    BtoSmall.push(A[j++]);
                th++;
                while(BtoSmall.size() >= th)  //语句1
                {
                    StoBig.push(BtoSmall.top());
                    BtoSmall.pop();
                }
                printf("%d
    ",StoBig.top());
                BtoSmall.push(StoBig.top());   //还给它,保证语句1能够成立
                StoBig.pop();
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    sqli-labs(30)
    sqli-labs(29)
    sqli-labs29-31关Background-6 服务器(两层)架构
    HA高可用的搭建
    克隆虚拟机,如何将克隆虚拟的网卡设置为eth0
    mysql1主多从配置
    关于mysql binlog日志的格式说明
    mysql主从同步
    tomcat的安装
    获取系统的IP
  • 原文地址:https://www.cnblogs.com/whatbeg/p/3574411.html
Copyright © 2011-2022 走看看