# UVa 10041 ### 題目連結:[UVa10041](http://domen111.github.io/UVa-Easy-Viewer/?10041) ### 題述: 世界聞名的黑社會老大Vito Deadstone要搬到紐約來了。在那裡他有一個大家族,並且他們都住在Lamafia大道上。因為Vito時常要拜訪所有的親戚,他想要找一間離他們最近的房子,也就是說他希望從他的家到所有的親戚的家的距離的和為最小。 他恐嚇你寫一個程式來幫助幫助他解決這個問題。 --- 輸入的第一列有一個整數代表以下有多少組測試資料。 每組測試資料一列,第一個整數 r(0 < r < 500),代表他親戚的數目。接下來的r個整數s~1~,s~2~,......s~r~為這些親戚房子的門牌號碼(0 < s~i~ <30000)。注意:有些親戚的門牌號碼會相同。 --- 對每一組測試資料,輸出從他的新家到所有的親戚的家的距離的和為最小為多少。2個門牌號碼s~i~、s~j~的距離為s~i~-s~j~的絕對值。 ### c++ code: ```cpp= #include<bits/stdc++.h> #include<cmath> #include<memory.h> using namespace std; int main() { //------------------------------------------------ #ifdef local freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); //------------------------------------------------ int t ; cin >> t ; int n ; while ( t-- ) { cin >> n ; int a[n] ; for ( int i = 0 ; i < n ; i++ ) { cin >> a[i] ; } sort ( a , a + n ) ; int min = a[0] ; int max = a[n - 1] ; int w = max - min + 1 ; int dis[w] ; memset ( dis , 0 , sizeof(dis) ) ; int q = 0 ; for ( int i = min ; i <= max ; i++ ) { for ( int j = 0 ; j < n ; j++ ) { dis[q] += abs( a[j] - i ) ; } q += 1 ; } sort ( dis , dis + w ) ; cout << dis[0] << endl ; } } ```  :::success **``sample input``** 3 2 2 4 3 2 4 6 4 2 1 999 5 ::: :::success **``sample output``** 2 4 1001 ::: #### [返回首頁](https://hackmd.io/@fkleofk/APCS#10041) ###### tags: `APCS選修` `C++` `UVa`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up