ACM1016中位数

问题描述:

  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.

意思:给出一组数据求中位数

输入:

  5
  2 4 1 3 5
 
输出:
  3
 代码:

#include <iostream>
#include<algorithm>
using namespace std;
bool com(int a,int b)
{
  return a < b;
}
int main()
{
  long num = 0;
  cin >> num;
  int * arr = new int[num];
  for(int i = 0;i < num;i++)
  {
    cin >> arr[i];
  }
  sort(arr,arr+num,com);
  if((num)%2)
  {
    cout << arr[num/2] << endl;
  }
  else  
  {
    int mid = (num)/2;
    cout << (arr[mid-1]+arr[mid])/2;
  }
  return 0;
}

 注意:数组的下标是从零开始的

posted @ 2016-03-19 12:39  SDAU_ZG  阅读(326)  评论(0编辑  收藏  举报