1. 程式人生 > >UVa 10041 Vito's Family

UVa 10041 Vito's Family

Background

The world-known gangster Vito Deadstone is moving to New York. He has a very big family there, all of them living in Lamafia Avenue. Since he will visit all his relatives very often, he is trying to find a house close to them.

Problem

Vito wants to minimize the total distance to all of them and has blackmailed you to write a program that solves his problem.

Input

The input consists of several test cases. The first line contains the number of test cases. For each test case you will be given the integer number of relatives r ( 0 < r < 500) and the street numbers (also integers) where they live ( 0 < si < 30000 ). Note that several relatives could live in the same street number.

Output

For each test case your program must write the minimal sum of distances from the optimal Vito’s house to each one of his relatives. The distance between two street numbers si and sj is dij= |si-sj|.

Sample Input

2 2 2 4 3 2 4 6

Sample Output

2 4

有一個人住在紐約,現在他有r個親戚,這個人經常會去所有的親戚家,現在他想找到一個房子,使得每一次他去訪問所有的親戚時候走的路是最短的,輸出這個最小值。

想了半天以為很麻煩,結果就是一個求中位數的題。 C語言程式碼如下:

#include<stdio.h>
#include<math.h>
int main()
{
	int n,a[505],t,j,temp;
	int sum;
	scanf("%d",&n);
	while(n--)
	{
		int i=0;
		scanf("%d",&t);
		for(i=0;i<t;i++)
		{
			scanf(" %d",&a[i]);
		}
		for(i=0;i<t;i++)
			for(j=0;j<t-i-1;j++)
				if(a[j]>a[j+1])
				{
					temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
		sum=0;
		temp=a[t/2];
			for(i=0;i<t;i++)
				sum+=abs(a[i]-temp);
		printf("%d\n",sum);
	}
	return 0;
}