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.
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.
* 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.
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);
}
欢迎大牛指教!!!