很大数量的数,求中位数
思路:此题不能存储所有元素,否则会MLE,想到用优先队列(默认值大的优先级高),存储一半,剩下的一半依次和队首比较,若小于队首,则将队首元素出队,新元素入队。
最后,若n为奇数,队首元素即为中间值;n为偶数,队列前两个的平均值为答案。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef unsigned int lint;
priority_queue<lint> pq;
int main()
{
int i, n;
lint val, t;
scanf("%d", &n);
for (i = 0; i <= n/2; ++i) {
scanf("%d", &val);
pq.push(val);
}
for (; i < n; ++i) {
scanf("%d", &val);
t = pq.top();
if (val < t) {
pq.pop();
pq.push(val);
}
}
double ans;
if (n&1)
ans = pq.top();
else {
ans = pq.top();
pq.pop();
ans += pq.top();
ans /= 2.0;
}
printf("%.1lf\n", ans);
return 0;
}