Spreading
the Wealth
Problem
A Communist regime is trying to redistribute wealth in a village. They have have decided tosit everyone around a circular table. First, everyone has converted all of their properties tocoins 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 rightand a number coins to the person on his left, such that in the end, everyone has thesame 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 anunsigned 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解題思路:本題運用中位元,先求均值,以確定移動情況,後求差值,確定移動具體數量,最後用中位元,確定移動定點(相當於參照點)。a[n]給她右邊的人xn個金幣,她左邊的人給她xn+1個金幣,av=a[n]-xn+xn+1.#include<cstdio>#include<algorithm>using namespace std;long long a[1000001],c[1000001];int main(){ int n,i,j; long long sum,av; while(scanf("%d",&n)!=EOF) { sum=0; for(i=1;i<=n;i++) { scanf("%lld",&a[i]); sum+=a[i]; } av=sum/n; //求均值 c[0]=0; for(i=1;i<=n;i++) c[i]=c[i-1]+a[i]-av; //求差值 sort(c,c+n); int x=c[n/2]; //求中位元 sum=0; for(i=0;i<n;i++) //求移動情況 sum+=abs(x-c[i]); printf("%lld\n",sum); } return 0;}