【JAVA】UVA 10041 - Vito's Family

UVa10041 Vito's family 題目原文:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=982

Sample Input
2
2 2 4
3 2 4 6
Sample Output
2
4

解題順序:

  1. 先將成員由小到大排序
  2. 找出該組成員的中位數
  3. 輸出中位數成員到各成員的距離總和。

現在來看範例:
Sample Input
2 <--這邊的2指的是有兩組要比對的資料
2 2 4 <--第一個2表示該組有2個成員,分別為2,4
3 2 4 6 <--該組有3個成員,分別為2,4,6
Sample Output
2 以2為中位數,所有成員與2的距離為|4-2|=2
4 以4為中位數,所有成員與4的距離為|2-4|+|6-4|=4

當成員數為偶數時,中間兩個數任意選一個即可。

import java.util.*;
public class main{
    public static void main(String[] args) {
     
            Scanner sc=new Scanner(System.in);
            int n= sc.nextInt(); //共幾組
            while((--n)>=0){
            
            int p = sc.nextInt(); //幾個成員
            int house[] = new int[p]; //令一個成員數大小的陣列
            
            for(int i = 0 ; i<p ; i++){
            	house[i] = sc.nextInt(); //輸入成員的值
            }
            
            Arrays.sort(house); //將成員由小到大排序
            
            int len=0;
            
            for(int i = 0 ; i<p ; i++){
            	len+=Math.abs(house[i]-house[i/2]); //計算所有成員與中位數的絕對值距離總和
            }
            System.out.println(len);
            }
    }
};