UVA

/*
  这题是我想岔了,最初是死算的,当然...超时了
  
  其实这道题不难
  首先应该将输入的位置排个序,找中位数,如果总数为奇数,可以直接找到;如果总是为偶数,找中间两个中的哪个都行,到其他点的距离之和都是相等的。(这点可以在纸上画4个位置的情况,自己验证一下);
  
  反正,其实是挺简单的一道题,之前一直没想清楚突破口是在哪,现在想明白了,就是排序后找中位数,偶数两个中位数,本来要分别讨论,找最小值的,但因为这两种情况,与其他位置的绝对值差,的和,是相等的,所以取哪个都可以
  
  另外,发现如果从0开始计数,而不从1开始,则由于整除的向下取整,找中位数时,甚至都可以不用分奇偶
  
  http://blog.csdn.net/jinjiahao5299/article/details/41519773
*/


#include <iostream>
#include <algorithm>
using namespace std;
int a[50];
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, sum = 0;
		cin >> n;
		for (int i = 0; i < n; i++) cin >> a[i];
		
		sort(a, a + n);
		int ans = 0, x;
	//	if (n & 1) 
		x = a[n>>1];
	//	else x = (a[n>>1] + a[(n>>1)-1]) >> 1;
		for (int i = 0; i < n; i++)
		if (a[i] > x) ans += a[i] - x;
		else ans += x - a[i];
		cout << ans << endl; 
	}
	return 0;
}


原文地址:https://www.cnblogs.com/mofushaohua/p/7789467.html