1.分治-找奶牛(中位数)

问题描述

 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)

速记

归并排序板子看一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熟人看不到

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值