1306. Sequence Median
Time limit: 1.0 second
Memory limit: 1 MB
Language limit: C, C++, Pascal
Memory limit: 1 MB
Language limit: C, C++, Pascal
Given a sequence of N nonnegative integers. Let's define the median of such sequence. If N is odd the median is the element with stands in the middle of the sequence after it is sorted.
One may notice that in this case the median has position (N+1)/2 in sorted sequence if sequence elements are numbered starting with 1. If N is even then the median is the semi-sum of the two "middle" elements of sorted sequence. I.e. semi-sum
of the elements in positions N/2 and (N/2)+1 of sorted sequence. But original sequence might be unsorted.
Your task is to write program to find the median of given sequence.
Input
The first line of input contains the only integer number N — the length of the sequence. Sequence itself follows in subsequent lines, one number in a line. The length of the sequence lies in
the range from 1 to 250000. Each element of the sequence is a positive integer not greater than 231−1 inclusive.
Output
You should print the value of the median with exactly one digit after decimal point.
Sample
| input | output |
|---|---|
4 3 6 4 5 |
4.5 |
Problem Source: II Collegiate Students Urals Programming Contest. Yekaterinburg, April 3-4, 1998
输出n个数的中位数,内存只允许存下n/2个数。因此只存排好序后的前n/2+1个数,就知道中位数了。用一个大根堆可以实现。
#include<cstdio>
#include<map>
#include<queue>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
#include<set>
#include<cmath>
using namespace std;
const int maxn = 1e5 + 5;
const int INF = 1e9;
const double eps = 1e-6;
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
#define fi first
#define se second
priority_queue<unsigned int> q;
int main(){
int n;
while(cin >> n){
while(!q.empty())
q.pop();
unsigned int x;
int mid = n/2+1;
for(int i = 0;i < mid;i++){
cin >> x;
q.push(x);
}
for(int i = mid;i < n;i++){
cin >> x;
unsigned int Max = q.top();
if(x < Max){
q.pop();
q.push(x);
}
}
if((n&1) == 0){
unsigned int a = q.top();
q.pop();
unsigned int b = q.top();
printf("%.1lf\n", (a+b)/2.0);
}
else{
unsigned int a = q.top();
printf("%.1lf\n", a*1.0);
}
}
return 0;
}
本文介绍了一种高效的方法来查找给定序列的中位数,仅需存储序列的一半元素即可确定中位数。
582

被折叠的 条评论
为什么被折叠?



