家族(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;
}