首页 > 代码库 > Poj 2388 Who's in the Middle

Poj 2388 Who's in the Middle

1.Link:

http://poj.org/problem?id=2388

2.Content:

Who‘s in the Middle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 31854 Accepted: 18541

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

Hint

INPUT DETAILS:

Five cows with milk outputs of 1..5

OUTPUT DETAILS:

1 and 2 are below 3; 4 and 5 are above 3.

Source

USACO 2004 November

3.Method:

 

4.Code:

 1 #include "iostream" 2 #include "stdlib.h" 3 #include "stdio.h" 4 #include <time.h> 5 #define N 10002 6 using namespace std; 7 int a[N]; 8 int Partition(int a[],int p,int r) 9 {10     int tmp = a[p];11     while(p<r)12     {13         while(p<r && a[r]>=tmp) r--;14         a[p]=a[r];15         while(p<r && a[p]<=tmp) p++;16         a[r]=a[p];17     }18     a[p]=tmp;19     return p;20 }21 int RandomizePartition(int a[],int p,int r)22 {23     int i = rand()%(r-p+1)+p;24     int tmp=a[i];25     a[i]=a[p];26     a[p]=tmp;27     return Partition(a,p,r);28 }29 30 int RandomizedSelect(int a[],int p,int r,int k)31 {32     if(p==r) return a[p];33     int i = RandomizePartition(a,p,r),j = i-p+1;34     if(k<=j) return RandomizedSelect(a,p,i,k);35     else return RandomizedSelect(a,i+1,r,k-j);36 }37 int main()38 {39     srand(time(NULL));//初始化随机数生成器40     int n;41     int i;42     scanf("%d",&n);43     for(i=0;i<n;i++) scanf("%d",&a[i]);44     //qsort(a,0,n-1);45     //printf("%d\n",a[n/2]);46     printf("%d\n",RandomizedSelect(a,0,n-1,(n+1)/2));47     system("pause");48     return 0;49 }

 

5.Reference:

Poj 2388 Who's in the Middle