题目分析:
0.堆
1.参考以下题解:
题解
code:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int main()
{
int T;
scanf("%d", &T);
while(T --)
{
int n, m;
scanf("%d%d", &m, &n);
printf("%d %d\n", m, (n + 1) / 2);
priority_queue<int>down;
priority_queue<int, vector<int>, greater<int>> up;
int cnt = 0;
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);
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)
{
printf("%d ", down.top());
if( ++cnt % 10 == 0) puts("");
}
}
if(cnt % 10 ) puts("");
}
return 0;
}
总结:
1.对顶堆:一个为大根堆,一个为小根堆。
性质:
1.1 当总元素为奇数时,down.top()是中位数。
1.2 读入一个元素x时,如果x<=down.top()则放入down,否则放入up。
1.3 down.size()数量严格比up.size()多1,谁多谁把堆顶移除到另外一个堆。