Workover
- Along a straight road there are N family households, due to the inconvenience of perennial water, and now the local government decided to finance repair a well to solve this problem. The staff of a road point is set to 0 point, so that N householders are located at points A1 ~ An. Please help them find appropriate workover position so that the various wells and the shortest distance, and calculates the shortest distance.
Input
a first output line N number of households, which 2≤N≤10000; 2 ~ N + 1 of the total number N of rows, the position of the occupant of Ai, where -10 9≤Ai≤10 . 9
Output
outputs a number representing the shortest distance
Sample Input
5
-1
-3
0
7
9
Sample Output
20
Analysis: If an odd number of households, well repair shortest distance is in the middle, if it is an even number of intermediate points to the selected average.
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
using namespace std;
int main()
{
int n,i;
long long int x,sum=0;
long long int a[10001];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%I64d",&a[i]);
}
sort(a,a+n);
if(n%2!=0)
{
x=a[n/2];
}
else
{
x=(a[n/2]+a[n/2-1])/2;
}
for(i=0;i<n;i++)
sum+=abs(a[i]-x);
printf("%I64d\n",sum);
return 0;
}