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. nlines 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
310010010041254
Sample Output
04
Problem setter: Josh Bao
题目链接:
分析:很好的题目。主要是分析的过程。具体看代码注释。
/*Uva 11300原来金币数为a1,a2,`````an.最终的金币为这些数的平均值,设为Axi表示i给i+1的金币个数a1+xn-x1=Aa2+x1-x2=Aa3+x2-x3=Aa4+x3-x4=A.......an+x(n-1)-xn=A利用后面n-1个等式,用x1表示 x2,x3,...xnx2=x1-(A-a2)x3=x1-(2*A-a2-a3);....结果就是求|x1|+|x1-b1|+|x1-b2|+...+|x1-b[n-1]|的最小值,取中位数*/#include#include #include #include #include using namespace std;const int MAXN=1000010;long long a[MAXN],b[MAXN];int main(){ int n; while(scanf("%d",&n) == 1) { long long sum=0; for(int i=1;i<=n;i++) { scanf("%I64d",&a[i]);//Uva上要用lld sum+=a[i]; } long long A=sum/n; b[0]=0; for(int i=1;i