Who's in the Middle
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 41955 |
|
Accepted: 24264 |
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
524135
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 USACO 2004 November |
這個題目是個排序的水題,因為題目給的資料全是整數,所以直接用庫函數裡的快排排個序就能解了。不過有一點要注意,n為偶數的時候,輸出的數是中間兩個的平均數。下面是My Code
#include <stdio.h>#include <stdlib.h>#define MAXN 10005int arr[MAXN];int cmp(const void*a,const void*b){ return *(int *)a-*(int *)b;}int main(){ int n; while(~scanf("%d",&n)) { for(int i=0; i<n; i++) scanf("%d",&arr[i]); qsort(arr,n,sizeof(int),cmp); if(n%2) printf("%d\n",arr[n/2]); else printf("%.1lf\n",(arr[n/2-1]+arr[n/2])/2.0); } return 0;} 一次AC,不過我在寫部落格的時候又發現了一個問題。如果n為偶數時,中間兩個數都是奇數或者都是偶數的時候應該輸出的是整數,而不像我寫的那樣,是出的是一位小數,那麼又要加個判斷語句,判斷是否為整數。可能是題目的資料問題吧,還是我理解錯了,不過能AC就對了。