uva 11300 Spreading the Wealth (中位数的应用)

                         uva 11300 Spreading the Wealth 

Problem

A Communist regime is trying to redistribute wealth in a village. They have have decided to sit everyone around a circular table. First, everyone has converted all of their properties to coins of equal value, such that the total number of coins is divisible by the number of people in the village. Finally, each person gives a number of coins to the person on his right and a number coins to the person on his left, such that in the end, everyone has the same number of coins. Given the number of coins of each person, compute the minimum number of coins that must be transferred using this method so that everyone has the same number of coins.

The Input

There is a number of inputs. Each input begins with n(n<1000001), the number of people in the village. n lines follow, giving the number of coins of each person in the village, in counterclockwise order around the table. The total number of coins will fit inside an unsigned 64 bit integer.

The Output

For each input, output the minimum number of coins that must be transferred on a single line.

Sample Input

3
100
100
100
4
1
2
5
4

Sample Output

0
4


题目大意:土财主分金币,把金币分给n个人(n<1000001),第一行数据为n,接下来n行为每个人分到的金币的数量。公平起见,每个人分到的金币都必须一样,所以拿金币多的要把金币匀给拿金币少的。匀金币的过程是这样的:每个人只能把金币匀给左边或右边的人(坐成环形)。求在匀金币过程中最小的金币移动数。


解题思路:设Mi为第i个人一开始拥有的金币数,x1为1号给四号x1个金币,也代表着4号受到一号给的x1个金币,设最终每个人拿到AVE个金币,则可得算式:

对于1号:M1 - x1 + x2 = AVE -> x2 = AVE - M1 + x1 = x1 - C1    (Ci = Mi + Mi-1 + Mi-2 +...+M1 -AVE)

对于2号:M2 - x2 + x3 = AVE -> x3 = AVE - M2 + x2 = 2AVE - M1 - M2 + x1 = x1 - C2

对于3号:M3 - x3 + x4 = AVE -> x4 = AVE - M3 + x3 = 3AVE - M1 - M2 - M3 + x1 = x1 - C3

.

.

.

所以最终我们所要的结果可以表达为:|x1| + |x1 - C1| + |x1 - C2| + ... + |x1 - Cn-1|

所以可以转化为求一点x1到线上Ci各点的最短距离,也就是”中位数“问题。


#include
#include
#include
#include
using namespace std;
long long peo[1000006];
long long m[1000006];
int main() {
	int n;
	while (scanf("%d", &n) == 1) {
		for (int i = 0; i < n; i++) {
			scanf("%lld", &peo[i]);	
		}
		long long ave, sum = 0;
		for (int i = 0; i < n; i++) {
			sum += peo[i];
		}
		ave = sum / n;
		m[0] = 0;
		for (int i = 1 ;i < n; i++) {
			m[i] = m[i - 1] + peo[i] - ave;
		}
		sort(m, m + n);
		long long min = 0, mid = m[n / 2];
		for (int i = 0; i < n; i++) {
			min += abs(mid - m[i]);
		}
		printf("%lld\n", min);
	}
	return 0;
}





你可能感兴趣的:(====ACM=====,大白)