Shortest Distance of HDU 2083 simple Edition

Source: Internet
Author: User

Problem Description
During the winter vacation, ACBOY visited many friends. It happened that all his friends were on the X axis of the coordinate plane. ACBOY can select a friend's home to start access, but he must go back to the starting point after each visit before accessing the next friend.
For example, if you have four friends, the corresponding X axis coordinates are 1, 2, 3, and 4. When ACBOY selects a point whose coordinate is 2 as the starting point, the final time required by ACBOY is | 1-2 | + | 2-2 | + | 3-2 | + | 4-2 | = 4.
Now, how can ACBOY take the least time to get the coordinates of N friends?

 


Input
The input is a positive integer M, indicating M test instances. Each instance has two input rows. The first is a positive integer N (N <= 500), indicating that there are N friends and the next row is a positive integer, represents the specific coordinates (all data is <= 10000 ).

 


Output
For each test instance, please output the minimum time it takes to access all friends, and the output of each instance occupies one line.

 


Sample Input
2
2
2 4
3
2 4 6


Sample Output
2
4

import java.io.BufferedInputStream;import java.util.*;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(new BufferedInputStream(System.in));int k,m,n;k=sc.nextInt();for(int i=0;i<k;i++){m=sc.nextInt();int a[]=new int[m];for(int j=0;j<a.length;j++){a[j]=sc.nextInt();}n=fun(m,a);System.out.println(n);}}public static int fun(int m,int a[]){int k,d=0;Arrays.sort(a);k=m/2;for(int i=0;i<a.length;i++){d+=Math.abs(a[i]-a[k]);}return d;}}

 

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.