a717困難雙堆維護逐次增加的排名

CPE:Black Box (UVa 501)

讓最大堆始終保存已需要的最小幾個元素。

前往題目練習 →回報教學錯誤每組時間 O((M+N) log M),空間 O(M)。

解題思路

第 p 次 GET 要求目前前綴的第 p 小。使用最大堆 low 保存最小的 p−1 個數,最小堆 high 保存其餘數,維持 low 中所有數都不大於 high。加入新數時先與 low 的堆頂比較,必要時把 low 最大者移到 high,保持 low 大小不變。

讀到查詢指定的加入數量後,把 high 最小者移入 low;此時 low 恰有 p 個元素,堆頂就是答案。查詢 u 可以重複,但排名仍會增加。重複數值各自入堆,不能去重。第一個數是測試組數,空白行可由 token 輸入略過,組間輸出一空行。

Step-by-step animation

示意:加入 3,1,−4;u=1,3

回報動畫錯誤
步驟 1 / 3

第一次查詢

加入 3,取 high 最小者。

low=[3]
high=[]
p
1
答案
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
int main() {
    int t;
    cin >> t;
    for (int cs = 0; cs < t; ++cs) {
        int m, n;
        cin >> m >> n;
        vector<int> a(m), u(n);
        for (int &x : a)
            cin >> x;
        for (int &x : u)
            cin >> x;
        priority_queue<int> low;
        priority_queue<int, vector<int>, greater<int>> high;
        int at = 0;
        if (cs)
            cout << '\n';
        for (int end : u) {
            while (at < end) {
                int x = a[at++];
                if (!low.empty() && x < low.top()) {
                    high.push(low.top());
                    low.pop();
                    low.push(x);
                } else
                    high.push(x);
            }
            low.push(high.top());
            high.pop();
            cout << low.top() << '\n';
        }
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多