UVa 11300 Spreading the Wealth 分金币 (中位数)

 F. 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


 

设第i号人目前手里拥有Ai枚金币

设第i号给了i-1号Xi枚金币,第1个人给了第n个人X1枚金币(因为圆桌),M表示为每人最终拥有的金币数

设Ci= A1 + A2 + A3 +...+ Ai  -  i *M; 

  可得  :

对于第一个人 A1- X1 + X2= M;  即 X2= M - A1 + X1   , X2=  X1 - C1;

对于第二个人 A2 - X2 + X3 = M;即 X3= M- A2 + X2 =  M- A2 + M - A2 +X1 =X1 -C2;

依次类推: Xn= x1- C(n-1);

题目要求被转手的金币和最少,即| x1 | + |x2| + ... +|Xn| 最小

| x1 | + |x2| + ... +|Xn| = |X1| + |X1 - C1| + .....+|X1- C(N-1)|

将X1取0,C1,C2,.....,C(N-1)的中位数时,该等式的值最小(证明见大白书)

代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<limits.h>
using namespace std;
long long a[1000010],c[1000010],sum,ans;
long long Fabs(long long x)
{
	return x > 0? x: -x;
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		sum= 0;
		for(int i= 1; i<= n; i++)
		{
			scanf("%lld",&a[i]);
			sum+= a[i];
		}
		long long ave= sum / n;
		c[0]= 0;
		for(int i= 1; i< n; i++)
			c[i]= c[i-1] + a[i] - ave; 
		sort(c,c+n);
		ans= 0;
		for(int i= 0; i< n; i++)
			ans+= Fabs(c[i]-c[n/2]);
		printf("%lld\n",ans);	
	}
	return 0;
}


 

你可能感兴趣的:(UVa 11300 Spreading the Wealth 分金币 (中位数))