Description
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
* Lines 2..N+1: Each line contains a single integer that is the milk output of one cow.
Output
Sample Input
5 2 4 1 3 5
Sample Output
3
題目就是求中位數,差不多用第k大的數的算法即可,我選擇快排改版
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int a[10005],n;
int Sort(int l,int r)
{
int x=a[l];
while(l<r)
{
while(a[r]>=x&&l<r)r--;
a[l]=a[r];
while(a[l]<=x&&l<r)l++;
a[r]=a[l];
}
a[l]=x;
return l;
}
int qsort(int l,int r,int k)
{
if(l>=r)return a[l];
int mid=Sort(l,r);
if(mid>k)return qsort(l,mid-1,k);
else if(mid<k)return qsort(mid+1,r,k);
return a[mid];
}
int main()
{
cin>>n;
int i;
for(i=1;i<=n;i++)cin>>a[i];
cout<<qsort(1,n,n/2+1);
}