Hdoj (HDU) 2083 simplified version of the shortest distance (median)

Source: Internet
Author: User

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); }
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.