现在的位置: 首页 > 综合 > 正文

uva 10041 Vito’s Family(检索)

2013年09月07日 ⁄ 综合 ⁄ 共 462字 ⁄ 字号 评论关闭

题目连接:10041 - Vito's Family


题目大意:给出所有邻居的位置,要求找到一个位置,使得该位置到所有邻居家的总和最小。


解题思路:就是单纯的找中位数,记得先排序, 然后将数组遍历一遍求的最小值。

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;

const int N = 30005;
int peo[N];

int main() {
    int cas, n, sum;
    scanf("%d", &cas);
    while (cas--) {
	sum = 0;
	memset(peo, 0, sizeof(peo));
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	    scanf("%d", &peo[i]);

	sort(peo, peo + n);

	int cur = peo[(n + 1) / 2 - 1];
	for (int i = 0; i < n; i++)
	    sum += abs(cur - peo[i]);
	printf("%d\n", sum);
    }
    return 0;
}

抱歉!评论已关闭.