求前奇数项的中位数
可以用对顶堆来维护,动态求中位数 时间复杂度$O(n\log{n})$
保证大根堆元素数量和小根堆元素数量相同(偶数个元素),或者刚好比小根堆元素数量多一个(奇数个元素)
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int N = 1e5 + 10;
int n;
priority_queue<int> heap1; // 大根堆
priority_queue<int, vector<int>, greater<int>> heap2; // 小根堆
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n;
for (int i = 1, x; i <= n; i++)
{
cin >> x;
if (heap1.empty() || x < heap1.top())
heap1.push(x);
else
heap2.push(x);
if (heap1.size() > heap2.size() + 1) {
heap2.push(heap1.top());
heap1.pop();
}
else if (heap1.size() < heap2.size() + 1){
heap1.push(heap2.top());
heap2.pop();
}
if (i % 2)
cout << heap1.top() << '\n';
}
return 0;
}