1. 程式人生 > >POJ2623 Sequence Median【中位數+排序】

POJ2623 Sequence Median【中位數+排序】

Sequence Median Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 17909 Accepted: 4964 Description

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 2^32 - 1 inclusive. Output

You should print the value of the median with exactly one digit after decimal point. Sample Input

4 3 6 4 5 Sample Output

4.5 Hint

Huge input,scanf is recommended. Source

Ural Collegiate Programming Contest 1998

問題連結:POJ2623 Sequence Median。

問題簡述:參見上文。

問題分析:

這是一個計算中位數問題,排序計算即可。

程式說明:

計算平均值需要使用double型別,不然會出問題。

因為要求提示會有大資料,所以用long long

且陣列要開大,不然會 RE

題記:

程式設計師要處處小心謹慎。

AC的C++語言程式如下:

#include<bits/stdc++.h> 

int main()
{
	long long  a[250000];
	long long  n;
	double mid;
	scanf("%lld",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%lld",&a[i]);
	}
	std::sort(a,a+n);
	if(n%2==0){
		mid=((double)a[n/2]+(double)a[n/2-1])/2;
	}
	else mid=(double)a[n/2];
	printf("%.1lf",mid);
	return 0;
}