AcWing 106. 动态中位数(对顶堆)

不得不说这种在线做法真的是十分精妙呢

传送门

#include <bits/stdc++.h>

using namespace std;

priority_queue<int, vector<int>, greater<int> > P; //小根堆
priority_queue<int, vector<int>, less<int> > Q; //大根堆

vector<int> ans;

int main() {
    //freopen("in", "r", stdin);
    int T, p, m, tmp;
    cin >> T;
    while (T--) {
        ans.clear();
        while (!P.empty())P.pop();
        while (!Q.empty())Q.pop();
        cin >> p >> m;
        for (int i = 1; i <= m; i++) {
            cin >> tmp;
            if (i == 1)
                P.push(tmp);
            else {
                int mid = P.top();
                if (tmp < mid)
                    Q.push(tmp);
                else
                    P.push(tmp);
            }

            if (P.size() > i / 2) {
                tmp = P.top();
                P.pop();
                Q.push(tmp);
            }
            if (Q.size() > (i - (i / 2 + 1))) {
                tmp = Q.top();
                Q.pop();
                P.push(tmp);
            }
            if (i & 1)
                ans.push_back(P.top());
        }
        cout << p << " " << (m + 1) / 2 << endl;
        for (int i = 1; i <= (m + 1) / 2; i++){
            cout << ans[i - 1] << " ";
            if (i % 10 == 0 )
                cout << endl;
        }
        cout << endl;
    }
    return 0;
}
上一篇:《NVM-Express-1_4-2019.06.10-Ratified》学习笔记(8.7)Standard Vendor Specific Command Format


下一篇:2019卖家放单平台有哪些is语音公会补单106房间找水清