POJ_2388 Who's in the Middle

来源:互联网 发布:http借口怎么写java 编辑:程序博客网 时间:2024/05/23 18:12
Who's in the Middle
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 26734 Accepted: 15432

Description

FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' cow gives: half of the cows give as much or more than the median; half give as much or less.

Given an odd number of cows N (1 <= N < 10,000) and their milk output (1..1,000,000), find the median amount of milk given such that at least half the cows give the same amount of milk or more and at least half give the same or less.

Input

* Line 1: A single integer N

* Lines 2..N+1: Each line contains a single integer that is the milk output of one cow.

Output

* Line 1: A single integer that is the median milk output.

Sample Input

524135

Sample Output

3

 

题意:一堆数中找中位数

思路:顺序统计(找第K大数)

代码如下:

#include<iostream>#define SIZE 10005using namespace std;int num[SIZE];void swap(int &a, int &b){int tmp;tmp = a;a = b;b = tmp;}int partition(int p, int r){int i,j,q;i = p - 1;q = num[r];for(j = p; j <= r - 1; j++){if(num[j] < q){i++;swap(num[i],num[j]);}}i++;swap(num[i],num[r]);return i;}int select(int p, int r, int i){int q,k;if(p == r)return num[p];q = partition(p, r);k = q - p + 1;if(i == k)return num[q];else if(i < k)return select(p,q - 1, i);elsereturn select(q + 1, r, i - k);}int main(){int i,n,p;cin >> n;for(i = 1; i <= n; i++){cin >> num[i];}p = select(1, n, n / 2 + 1);cout << p << endl;return 0;}