Spreading the Wealth
题目
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.
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.
Output
For each input, output the minimum number of coins that must be transferred on a single line.
Simple Input
3
100
100
100
4
1
2
5
4
Simple Output
0 4
一句话题意
有n个人围圆桌而坐,每个人有Ai个金币,可以给左右相邻的人一些金币,使得最终所有人金币数相等,求最小金币转移数。
大致思路
对于任意的人i,他所有的关系只有两种,给i-1金币,从i+1得金币,设每个人最终应该有m个金币(金币数除以人数得m),m就可求。
根据上述所说,可以看做一个数列一样的东西,但并不是。可以用给第一个人的金币来表示所有人的,即如下所示:
x2=x1-A[i]+m;
x3=x2-A2+m=x1-A[1]-A[2]+2m;
x4=x3-A3+m=x1-A[1]-A[2]-A[3]+3m;
···
利用一个数组简化一下上边的式子:
令x2=x1-c[1];
x3=x2-c[2];
然后就能推出c[i]=c[i-1]+a[i]-m
然后利用这个,找到一个x1使所有c数组里的数值与x1做差所得的和最小,所以就可以推出c数组中数据的中位数是答案。
代码
#include<iostream> #include<cstring> #include<algorithm> #include<cmath> using namespace std; typedef long long ll; const int maxn = 1e6 + 5; ll A[maxn]; ll C[maxn]; ll n; ll sum; ll m; int main(){ while (~scanf("%d",&n)){ memset(A, 0, sizeof(A)); memset(C, 0, sizeof(C)); sum = 0; for (int i = 1; i <= n; i++){ scanf("%d",&A[i]); sum += A[i]; } m = sum / n; for (int i = 1; i < n; i++){ C[i] = C[i - 1] + A[i] - m; } sort(C, C + n); ll x1 = C[n / 2], ans = 0; for (int i = 0; i < n; i++){ ans += abs(x1 - C[i]); } printf("%d\n",ans); } return 0; }