Vito 必須住在門牌號碼為中位數那一家,方能使他到其它人家裡的距離達到最小值。
有錯或有問題請多多指教、留言
網址:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=982
--------------------------------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int cmp(const void *, const void *);
int main()
{
int _case, relatives, *street_num = NULL, temp, median, sum, i;
scanf("%d", &_case);
while(_case--)
{
scanf("%d", &relatives);
temp = relatives;
street_num = malloc(relatives*sizeof(int) ); /* Dynamic memory allocation. */
while(temp--)
scanf("%d", street_num+temp);
qsort( (void *)street_num, relatives, sizeof(int), cmp);
temp = relatives-1; /* index */
median = street_num[temp/2]; /* Vito must live in median street number. */
for(i = 0, sum = 0; i < relatives; i++)
sum += abs(median - street_num[i]);
printf("%d\n", sum);
}
free( (void *)street_num);
street_num = NULL;
return 0;
}
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
--2017-05-22----------------------------------------------------------------------------------------------------------------------
package vito.s_family;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author awesq
*/
public class main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int testCases, array[] = new int[10000];
Scanner sc = new Scanner(System.in);
testCases = sc.nextInt();
while (testCases-- > 0) {
int numOfRelatives = sc.nextInt();
for (int i = 0; i < numOfRelatives; i++) {
array[i] = sc.nextInt();
}
Arrays.sort(array, 0, numOfRelatives);
// public static void sort(int[] a,
// int fromIndex,
// int toIndex)
// The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive.
int median = array[(numOfRelatives - 1) / 2], sum = 0;
for (int i = 0; i < numOfRelatives; i++) {
sum += Math.abs(median - array[i]);
}
System.out.println("" + sum);
}
}
}