题目链接:​​https://www.luogu.com.cn/problem/P1168​

解题思路:
开一个大根堆维护前 \(\lfloor \frac{i}{2} \rfloor\) 个较小的元素;
开一个小根堆维护前 \(\lceil \frac{i}{2} \rceil\) 个较大的元素。

然后每次碰到奇数 \(i\) ,中位数即为小根堆的堆顶元素。

这里使用优先队列(priority_queue)来模拟堆。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
int n, a;
priority_queue<int> big_heap;
priority_queue<int, vector<int>, greater<int> > small_heap;
int main() {
cin >> n;
for (int i = 1; i <= n; i ++) {
cin >> a;
if (i==1 || a <= big_heap.top()) big_heap.push(a);
else small_heap.push(a);
if (big_heap.size() > i/2) {
small_heap.push(big_heap.top());
big_heap.pop();
}
if (small_heap.size() > (i+1)/2) {
big_heap.push(small_heap.top());
small_heap.pop();
}
if (i % 2)
cout << small_heap.top() << endl;
}
return 0;
}