UVA 11300
Maths problem.
xi means the ith person gives xi coins to the (i - 1)th person. If the first person gvies 2 coins to the second and the second gives 3 coins to the first, then x2 is = 3 - 2 =1.
And what we want to solve is how to make answer = ∑abs(x[i]) is the least.
average = total_coins / n.
So we could obtain the equations below:
money[0] - x[0] + x[1] = average.
money[1] - x[1] + x[2] = average.
money[2] - x[2] + x[3] = average.
...
money[n] - x[n] + x[0] = average. (Note: It's a circle. But this equation is useless, since we can get it from the former n - 1 ones.)
So we could know this:
x[1] = x[0] - (money[0] - average).
x[2] = x[1] - (money[1] - average).
...
x[n] = x[n - 1] - (money[n - 1] - average).
We can easily obtain:
x[i] = x[0] - [(money[0] + money[1] +... + money[i - 1]) - i *average].
set C[i] = [(money[0] + money[1] +... + money[i - 1]) - i *average], C[0] = 0.
So x[i] = x[0] - C[i].
And answer = ∑abs(x[i]) = ∑abs(x[0] - C[i]) is the least.
Sort the C array.
So the x[0] should be the median number in C array.
so answer = ∑abs(C[n / 2] - C[i]).
Via:
《算法竞赛入门经典训练指南》