很大數量的數,求中位數
思路:此題不能存儲所有元素,否則會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;
}