北大OJ:2388:Who's in the Middle

本文介绍了一道经典的算法题目,旨在找出一组奶牛中产奶量处于中间位置的那只,即中位数。通过使用快速排序算法实现,确保至少一半的奶牛产奶量不低于该中位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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


分析:

        分析题目发现,题目本质为排序并输出中位数,故采用快速排序法先进行排序,再输出中位数。

解题代码:

#include<iostream>
using namespace std;
void sort(int[],int,int);  //排序函数声明
int main()
{
	int n;
	cin>>n;

	//动态生成数组
	int *a=new int[n];
	for(int i=0;i<n;i++)
		cin>>a[i];
	//快速排序
	sort(a,0,n-1);
	//输出中位数
	cout<<a[(n-1)/2]<<endl;
}


 //查找轴值
int findpivot(int A[],int i,int j)
{
	return (i+j)/2;
}


//分割数组
int partition (int A[],int l,int r,int& pivot)
{
	int temp;
	do{
		while(A[++l]<pivot);
		while((r!=0)&&(A[--r]>pivot));

		temp=A[l];
	    A[l]=A[r];
	    A[r]=temp;
	}while(l<r);

	temp=A[l];
	A[l]=A[r];
	A[r]=temp;
	return l;
}



//快速排序函数
void sort(int A[],int i,int j)
{ 
	int temp;

	if(j<=i)
		return;   //数组元素过少
	int pivotindex=findpivot(A,i,j);   //查找轴值
	//将轴值放到最后
	temp=A[j];
	A[j]=A[pivotindex];
	A[pivotindex]=temp;

	int k=partition(A,i-1,j,A[j]);     //分割数组

	temp=A[j];
	A[j]=A[k];
	A[k]=temp;

	sort(A,i,k-1);
	sort(A,k+1,j);

}



欢迎大牛指教!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值