家族 题解

家族(family.cpp)
【问题描述】
著名的大盗Vito Deadstone将到纽约去。在那里,他有一个庞大的家族,所有人都住在Lamafia大道。因为会经常拜访这些亲戚,他希望找一间离他们很近的房子。
事实上,Vito希望让他的房子离所有亲戚的距离之和尽量小。他命令你写一个程序来解决这一问题。
【输入格式】
输入包含若干个测试点。第一行为测试点的数量。
对于每组数据,你将会得到整数r(0<r<500),表示Vito的亲戚数量以及他们所居住的街编号(也是整数)s1 , s2 ,… , si , … sr ,其中0 < si <30000。可能会有不同的亲戚住在同一条街上。
【输出格式】
对于每一组数据,你的程序要输出从Vito的房子离所有亲戚家的总距离的最小值。si和sj两条街之间的距离dij = |si-sj|。
【时限,空间要求】
1秒,128M。
【输入输出样例】
family.in
family.out
2
2 2 4
3 2 4 6
2
4

// 一组数据,如果要求一个数,该数与所有数据的差的绝对值和最小,则该数是这组数据的中位数。   
      
#include <iostream>  
#include <algorithm> 
#include <cstdio> 
      
using namespace std;  
      
#define MAXSIZE 500  
      
int main(int ac, char *av[])  
{  
    int cases, total;  
    int address[MAXSIZE];  
    freopen("family.in","r",stdin);
    freopen("family.out","w",stdout);
      
    cin >> cases;  
    while (cases--)  
    {  
        cin >> total;  
        int counter = 0;  
        while (counter < total)  
            cin >> address[counter++];  
      
        sort(address, address + total);  
      
        // 找到中位数并求和,注意该题所求的中位数须为整数。  
        int middle;  
        if (total & 1)  
            middle = address[total / 2];  
        else  
            middle = (int) (((float) (address[total / 2 - 1] +  
                    address[total / 2]) * 5.0 + 5.0) / 10.0);  
      
        long shortest = 0;  
      
        for (int i = 0; i < total; i++)  
        {  
            int distance = middle - address[i];  
            shortest += (distance >= 0 ? distance : (-1) * distance);  
        }  
      
        cout << shortest << endl;  
    }  
      
    fclose(stdin);
    fclose(stdout);
	return 0;  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值