hdu 2083

来源:互联网 发布:oracle 查看数据库ip 编辑:程序博客网 时间:2024/06/14 02:02

刷水题啊,哈哈哈,这是道中位数题目,给你几个点求取哪个点,使得其他点到这点的距离总和最小

这个点就是排序后的中位数点,想想为什么?

1 2 3 4 5 6 7

这7个点中,中位数为4,当选取的点不在4时,如选5,则1~4个点到中心点的距离都要增加1,5~7的距离要减少1,4个增1,3个减一,显然就是中位数最小啦

#include<stdio.h>#include<math.h>int cmp(const void *a,const void *b){    return *((int*)a)-*((int *)b);}void main(){    int T,n,i,b[501],ans;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        for(i = 0;i < n;i++)            scanf("%d",&b[i]);        qsort(b,n,sizeof(b[0]),cmp);        for(i = 0,ans = 0;i < n;i++)            ans += fabs(b[i]-b[(n-1)/2]);        printf("%d\n",ans);    }}