Problem Description
Winter vacation, Acboy to visit a lot of friends, happened to all his friends home in the coordinate plane of the x axis. Acboy can choose a friend's home to start a visit, but after each visit he has to go back to the starting point before he can visit his next friend.
For example, there are 4 friends, the corresponding x axis coordinates are 1, 2, 3, 4. When the Acboy selects the point with coordinates 2 as the starting point, the time he eventually takes is |1-2|+|2-2|+|3-2|+|4-2| = 4.
Now give the coordinates of n friends, then how Acboy should go to spend the least time.
Input
The input is first a positive integer m, representing the M test instance. The input of each instance has 2 rows, first is a positive integer n (n <= 500), which means that there are N friends, and the next line is n positive integers, representing the specific coordinates (all data are <=10000).
Output
For each test instance, print out the minimum time spent accessing all your friends, and the output of each instance is in one row.
Sample Input
2
2
2 4
3
2 4 6
Sample Output
2
4
It's a very simple question.
First, the distance to the friend of the coordinates of the order, and then select the median will be OK.
Analyze the lowest point:
When n is odd, the lowest point is N/2. When n is an even number, the lowest point is a A[N/2-1]~A[N/2] segment. Since it is a point, then choose whichever of the two intermediate points.
import java.util.Arrays; import Java.util.Scanner;
public class main{public static void Main (string[] args) {Scanner sc = new Scanner (system.in);
int t = Sc.nextint ();
while (t-->0) {int n =sc.nextint ();
int a[] = new Int[n];
for (int i=0;i<n;i++) {a[i]=sc.nextint ();
} arrays.sort (a);
int num=0;
for (int i=0;i<n;i++) {num + + (int) math.abs (a[n/2]-a[i]);
} System.out.println (num); }
}
}