POJ 1442 Black Box 优先队列题解

2017-10-30  本文已影响0人  失树

原题链接

Black Box

#include<iostream>
#include<queue>
#include<vector>
#define MAXM 30005
#define MAXN 30005
int num[MAXM] = { 0 };
int op[MAXN] = { 0 };
using namespace std;
template<class T>
class Greater {
public:
    bool operator()(const T& a, const T& b) {
        return a > b;
    }
};
priority_queue<int, vector<int>, less<int> > a;     //大顶堆
priority_queue<int, vector<int>, Greater<int> > b;  //小顶堆
int main() {
    int M, N;
    cin >> M >> N;
    for (int i = 1; i <= M; i++) {
        cin >> num[i];
    }
    for (int i = 1; i <= N; i++) {
        cin >> op[i];
    }
    int cnt = 0;
    int cursor = 1;
    while (cnt < M) {
        cnt++;
        b.push(num[cnt]);
        if (a.empty()) {//初始化
            a.push(b.top());
            b.pop();
        }
        else if (!b.empty() && a.top() > b.top()) {
            int t = a.top();
            a.pop();
            a.push(b.top());
            b.pop();
            b.push(t);
        }
        while (cursor<=M&&op[cursor] == cnt) {//输出时刻
            cursor++;
            cout << a.top() << endl;
            if (!b.empty()) {
                a.push(b.top());
                b.pop();
            }
            else {
                cnt++;
                a.push(num[cnt]);
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读