优先队列 || POJ 1442 Black Box

给n个数,依次按顺序插入,第二行m个数,a[i]=b表示在第b次插入后输出第i小的数
*解法:写两个优先队列,q1里由大到小排,q2由小到大排,保持q2中有i-1个元素,那么第i小的元素就是q2的top
而且注意到每次输出第i小的数i都是递增的
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
#define SZ 30005
#define INF 1e9+10
int a[SZ];
priority_queue<int> q1, q2;
int main()
{
    int n, m, b;
    scanf("%d %d", &n, &m);
    for(int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    int j = 0;
    for(int i = 1; i <= m; i++)
    {
        scanf("%d", &b);//在第b次插入后输出第i小的元素,保证q1中始终有i-1个元素
        while(j < b)
        {
            if(q1.empty() || a[j] > q1.top())//把empty的判断放在前面,否则访问top会RE
            {
                q2.push(-a[j]);
            }
            else
            {
                int tmp = q1.top();
                q1.pop();
                q1.push(a[j]);
                q2.push(-tmp);
            }
            j++;
        }
        int tmp = -q2.top(); q2.pop();
        printf("%d
", tmp);
        q1.push(tmp);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pinkglightning/p/8405432.html