POJ 1442 Black Box ----- 优先队列

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=5857

题意:给定n个数和m个时刻,i=1,从1时刻开始每时刻添加1个数,每当当前时刻在m个给定时间中时,执行一次get操作,即输出数列中第i小的数,i++

题解:https://blog.csdn.net/yeguxin/article/details/47258241

类似求第k小数这种题,可以考虑大顶堆(优先队列)q2,q2里面尽量装i个数,这i个数是当前所有数里面最小的,则第i小的数直接q2.top()即可,不够i个数则去剩下的数里面找,剩下的数用小顶堆排即可。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int maxn =30010; 
int n, m;
int a[maxn], b[maxn];
int cnt;

int main() {
   while(scanf("%d%d", &n, &m) != EOF) {
       for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
       priority_queue<int ,vector<int>, greater<int> > q1;
       priority_queue<int ,vector<int>, less<int> > q2;
        while(!q1.empty())
        {
            q1.pop();
        }
        while(!q2.empty())
        {
            q2.pop();
        }
       int ans = 0;
       for(int i = 1; i <= m; i++) {
           scanf("%d", &cnt);
           for(int j = ans + 1; j <= cnt; j++) {
               if(q2.size() < i) q2.push(a[j]);
               else if(a[j] < q2.top()) {
                   q1.push(q2.top());
                   q2.pop();
                   q2.push(a[j]);
               } else {
                   q1.push(a[j]);
               }
           }
           if(q2.size() < i) {
               int num = i - q2.size();
               for(int k = 1; k < num; k++) {
                   b[k] = q1.top();
                   q1.pop();
               }
               printf("%d\n", q1.top());
               for(int k = 1; k < num; k++) {
                   q1.push(b[k]);
               }
           } else
           
           printf("%d\n", q2.top());
           ans = cnt;
           if(!q1.empty()) {
               q2.push(q1.top());
               q1.pop();
           }
       }
   }
    
    
    
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值