Question: uva10057-a mid-summer Night's Dream
Given N number, a makes (| X1-A | + | X2-A | +... ... + | Xn-A |) is minimum. Calculate the minimum a value. Enter the number of A values and the number of A values. (A may have multiple values)
Solution: to minimize the formula above, find the median of the N number. If it is an odd number, there is only one median, and there is only one number of different. If a is an even number, the median value is composed of two values. Then, to find the number of A in the input value, we need to find the number and of the two values, the number of different A values is the right median-the left median + 1;
Example:
3 5 6 9 11 13 median 6 and 9
3 5 6 | 9 11 13
Deviation 3 1 0 | 3 5 7 A = 6
The sum of the left half side plus 1 and the right half side minus 1 is still the smallest.
4 2 1 | 2 4 6 A = 7
5 3 2 | 1 3 5 A = 8
6 4 1 | 0 2 4 A = 9 the right half side has a value of 0, indicating that it cannot be reduced.
So the possible A: 6 7 8 9
Code:
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>using namespace std;const int N = 1000005;int n;int num[N];int main () {int mm, count, ans;while (scanf ("%d", &n) != EOF) {for (int i = 0; i < n; i++) scanf ("%d", &num[i]);sort (num, num + n);count = 0;if (n % 2) {mm = num[n / 2];for (int i = n / 2; i >= 0 && num[i] == mm; i--)count++;for (int i = n / 2 + 1; i < n && num[i] == mm; i++)count++;ans = 1;} else {int left = num[n / 2 - 1];int right = num[n / 2];mm = left;for (int i = n / 2 - 1; i >= 0 && num[i] == left; i--)count++;for (int i = n / 2; i < n && num[i] == right; i++)count++;ans = right - left + 1;}printf ("%d %d %d\n", mm, count, ans);}return 0;}