#9278: 意義


simultaneously (----------以上是高手------------)

學校 : 高雄市立新莊高級中學
編號 : 37268
來源 : [1.200.206.195]
最後登入時間 :
2018-12-01 11:50:33
d452. 二、直線最小距離和 -- 98學年度板橋高中校內資訊學科能力競賽 | From: [111.254.219.147] | 發表日期 : 2014-10-04 21:27

此題的意義是"找出排序後的中位數"

為何?因為中位數是最中間的數字,所以對於每個數字來講就像一堆建築物繞著一個龐然大物一樣

能以最小的距離到達

所以才要用中位數,以下是我的程式碼

 #include<cstdio>

#include<algorithm>

using namespace std;

int abs(int x){

    return (x>0?x:-x);

    }

int main(){

    int t,m;

    while(~scanf("%d",&t)){

    while(t--){

    scanf("%d",&m);

    int a[m],sum=0;

   for(int i=0;i<m;i++) scanf("%d",&a[i]);

   sort(a,a+m);//內建排序

   for(int i=0;i<m;i++) sum+=abs(a[i]-a[m/2]);//為防止有負數結果,用絕對值

   printf("%d\n",sum);

}} }


 

 
ZeroJudge Forum