题目链接:http://exam.upc.edu.cn/problem.php?cid=1430&pid=15
题意:
给定数列a[1-n],起初有a[1]。每次输入两个数,输出当前数组的中位数
思路:
利用对顶堆求中位数,每次将输入的两个数分别插入最小堆和最大堆中,维护对顶堆,使最大堆的最大值(堆顶元素)小于最小堆的最小值(堆顶元素)。每次添加两个数后都可计算出此时的中位数——最大堆的堆顶元素。
代码:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e4+5;
int n, m, temp[maxn], ans[maxn];
int main()
{
int t;
scanf("%d", &t);
while(t--){
priority_queue<int,vector<int>,less<int> >a;
priority_queue<int,vector<int>,greater<int> >b;
scanf("%d%d", &m, &n);
for(int i=1; i<=n; ++i) scanf("%d", &temp[i]);
printf("%d %d\n", m, (n+1)/2);
int cnt = 0;
a.push(temp[1]); ans[++cnt]=temp[1];
for(int i=2; i<=n; i+=2){
b.push(temp[i]), a.push(temp[i+1]);
while(a.top()>b.top()){
int _a = a.top(), _b = b.top();
a.pop(), b.pop();
a.push(_b), b.push(_a);
}
ans[++cnt] = a.top();
}
int i;
for(i=1; i<=cnt; ++i)
printf("%d%c", ans[i], (i%10==0)?'\n':' ');
if(i%10!=0) printf("\n");
}
}