Language:
Default
Who’s in the Middle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 51776 Accepted: 29786
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.
分析:简单的排序,注意交换函数的写法(我在这翻车了。。。)
sort也能过。。。
#include<iostream>
using namespace std;
const int maxn=10010;
int data[maxn];
void myswap(int &a,int &b)
{
int t;
t=a;
a=b;
b=t;
}
int Partition(int left,int right)
{
int i=left;
int temp=data[right];
for(int j=left;j<right;j++)
if(data[j]<temp)
{
myswap(data[j],data[i]);
i++;
}
myswap(data[i],data[right]);
return i;
}
void quicksort(int left,int right)
{
if(left<right)
{
int i=Partition(left,right);
quicksort(left,i-1);
quicksort(i+1,right);
}
}
int main()
{
int n,i;
while(cin>>n)
{
for(i=1;i<=n;i++)
{
cin>>data[i];
}
quicksort(1,n);
cout<<data[(n+1)/2]<<endl;
}
return 0;
}