POJ 2388 Who's in the Middle

Who's in the Middle
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 26878   Accepted: 15526

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

5
2
4
1
3
5

Sample Output

3

一道大水题,把给的数据存入数组,排序后输出中间那个即可
学了一下堆排序,所以就用堆排序写的,估计正常来写快排就可以

 1  #include<iostream>
 2 
 3  using namespace std;
 4 
 5  long milk[10010];
 6 
 7  void HeapAdjust(int s,int length)
 8  {
 9      int i;
10      long temp=milk[s];
11      for(i=2*s;i<=length;i*=2)
12      {
13          if(i<length&&milk[i]<milk[i+1])
14             ++i;
15          if(temp>=milk[i])
16             break;
17          milk[s]=milk[i];
18          s=i;
19      }
20      milk[s]=temp;
21  }
22 
23  int main()
24  {
25      int n;
26 
27      cin>>n;
28 
29      for(int i=1;i<=n;i++)
30         cin>>milk[i];
31 
32      for(int i=n/2;i>=1;i--)
33         HeapAdjust(i,n);
34 
35      for(int i=n;i>1;i--)
36      {
37          long temp=milk[1];
38          milk[1]=milk[i];
39          milk[i]=temp;
40          HeapAdjust(1,i-1);
41      }
42 
43     cout<<milk[n/2+1]<<endl;
44 
45      return 0;
46  }
[C++]

 

posted @ 2013-05-27 16:44  ~~Snail~~  阅读(148)  评论(0编辑  收藏  举报