# UVA 10041 Vito's Family ## 題目連結 [UVA 10041](https://vjudge.net/problem/UVA-10041) ### 題目內容 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. Vito wants to minimize the total distance to all of them and has blackmailed you to write a program that solves his problem. ### 輸入限制 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) s1, s2, . . . , si, . . . , sr where they live (0 < si < 30000 ). Note that several relatives could live in the same street number. ### 輸出限制 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 |. ### 解題思路 這題要求最短路徑,先將a陣列做排序,再求中間值,中間值就是他們家的位置,接下來只要算出與其他每家的距離就好。 ### 程式碼 ```c++ #include<bits/stdc++.h> using namespace std; long long a[505]; int main(){ int kase; cin>>kase; while(kase--){ memset(a,0,sizeof a); long long n,temp=0,ans=0; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } sort(a,a+n); temp=a[n/2]; for(int i=0;i<n;i++){ ans+=abs(temp-a[i]); } cout<<ans<<endl; } } ``` ## 測資 ### Sample input 3 2 2 4 3 2 4 6 4 2 1 999 5 ### Sample output 2 4 1001 ## 中文題目連結 [zerojudge a737](https://zerojudge.tw/ShowProblem?problemid=a737)