← 返回题目页

P1168 中位数

标程

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    // low:大根堆,存较小的那一半;high:小根堆,存较大的那一半。
    // 始终保持 low 的元素个数 == high 的个数,或者比 high 多 1。
    priority_queue<int> low;
    priority_queue<int, vector<int>, greater<int>> high;

    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        if (low.empty() || x <= low.top()) low.push(x);
        else high.push(x);

        if (low.size() > high.size() + 1) {
            high.push(low.top());
            low.pop();
        } else if (high.size() > low.size()) {
            low.push(high.top());
            high.pop();
        }

        // 只在读入奇数个元素时输出中位数
        if ((i + 1) % 2 == 1) cout << low.top() << "\n";
    }
    return 0;
}

动画演示