问题描述
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.
翻译
FJ 正在调查他的牛群,以找出最平均的奶牛。他想知道这头 "中位数 "奶牛的产奶量:一半奶牛的产奶量与中位数相当或更高;一半奶牛的产奶量与中位数相当或更低。给定奇数头奶牛 N(1 <= N < 10,000)和它们的产奶量(1...1,000,000),求奶牛产奶量的中位数,使得至少一半奶牛产奶量相同或更多,至少一半奶牛产奶量相同或更少。
寻找中位数产奶奶牛
思路
归并排序
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
const int N=1e6+10;
void mergeSort(int a[], int l, int r)
{
if (l >= r)return;
int mid = l + r >> 1,i=l,j=mid+1,k=0;
mergeSort(a, l, mid);
mergeSort(a, mid + 1, r);
while (i <= mid && j <= r)
{
if (a[i] <= a[j])
ans[k++] = a[i++];
else
ans[k++] = a[j++];
}
while(i<=mid)
ans[k++] = a[i++];
while(j<=r)
ans[k++] = a[j++];
for (int i = l, j = 0; i <= r; i++, j++)
a[i] = ans[j];
}
int main()
{
int n;
cin >> n;
int a[N] = { 0 };
cout << "The arr before sorting is following :" << endl;
for (int i = 0; i < n; i++)
{
a[i] = rand();//cin>>a[i];
cout << a[i] << " ";
}
cout << endl;
mergeSort(a, 0, n-1);
cout << "The arr after sorting is following :" << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << "\n The most average cow gives " << a[n / 2]<<" milk "<<endl;
return 0;
}
测试案例
随机生成
运行结果
时间复杂度分析
O(nlogn)
速记
归并排序板子看一下