本题动态中位数,可以选用大根堆和小根堆,
大根堆,就是底部大,上面数字小的堆,priority_queue< int > down来写
小根堆, 与之相反, priority_queue< int, vector< int >, greater< int >> up,来写
直接看代码吧, 会定义就差不多能写出来了。
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
int T;
int n, m;
int main()
{
cin >> T;
while (T -- )
{
int cnt = 0;
priority_queue<int> down;
priority_queue<int, vector<int>, greater<int>> up;
cin >> m >> n;
cout << m << ' ' << (n / 2) + 1 << endl;
for (int i = 1; i <= n; i ++ )
{
int x;
scanf("%d", &x);
if (down.empty() || x < down.top()) down.push(x);
else up.push(x);
//枚举奇数个数的时候,要保证down比up多一个,偶数个数的时候,一样多
if (down.size() > up.size() + 1) up.push(down.top()), down.pop();
if (up.size() > down.size()) down.push(up.top()), up.pop();
if (i % 2)
{
cout << down.top() << ' ';
if (++ cnt % 10 == 0) puts("");
}
}
if (cnt % 10) puts("");
}
}