1306. Sequence Median
Time limit: 1.0 second
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
Tags: data structures unusual problem (hide tags for unsolved problems)
Difficulty: 153
题意:求n个数的中位数
分析:注意看空间限制。。。
显然,我们只能存下一半的数据,
怎么办呢。。。。
。。。。
那我们就存最大的那一半(n / 2 + 1)数据就好了。。
。。。然后我们就用一个堆或者其他什么存下来。。。
偶数就去存下来的前两个,奇数就取存下来的第一个
用优先队列是不行的,因为优先队列申请空间是一段一段的。。。
只能用make_heap了
1 #include <cstdio> 2 #include <queue> 3 #include <iostream> 4 using namespace std; 5 inline void SetIO(string Name) 6 { 7 string Input = Name+".in", 8 Output = Name+".out"; 9 freopen(Input.c_str(), "r", stdin), 10 freopen(Output.c_str(), "w", stdout); 11 } 12 13 int n, Arr[250000 / 2 + 5]; 14 15 inline void Input() 16 { 17 scanf("%d", &n); 18 } 19 20 inline void Solve() 21 { 22 for(int i = 0; i < n / 2 + 1; i++) scanf("%d", &Arr[i]); 23 make_heap(Arr, Arr + n / 2 + 1); 24 for(int i = n / 2 + 1; i < n; i++) 25 { 26 scanf("%d", &Arr[n / 2 + 1]); 27 push_heap(Arr, Arr + n / 2 + 2); 28 pop_heap(Arr, Arr + n / 2 + 2); 29 } 30 if(n & 1) printf("%.1lf\n",1.0 * Arr[0]); 31 else 32 { 33 unsigned int x = Arr[0]; 34 pop_heap(Arr, Arr + n / 2 + 1); 35 unsigned int y = Arr[0]; 36 printf("%.1lf\n", 1.0 * (x + y) / 2.0); 37 } 38 } 39 40 int main() 41 { 42 #ifndef ONLINE_JUDGE 43 SetIO("G"); 44 #endif 45 Input(); 46 Solve(); 47 return 0; 48 }