题目
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.
Sample Input
3
100
100
100
4
1
2
5
4
Sample Output
0
4
题意:
n个人坐成一圈,第i个人有book[i]个金币,这个人可以给他相邻的两个人任意数量的金币,为了让每个人的金币的数量都相同,问转移的金币的数量最少是多少?
分析:
刚开始看这道题的时候就想到了那个合并石头那道题,感觉还挺像的!
我们设第i个位置的人给了第i-1个人x1个金币,从第i+1个人那里得到了x2个金币,以此类推;金币得平均值为avg;则我们可以列出如下得式子:
book[i]-Xi+X(i+1)=avg
那么第一个人的金币变化为:
book[1]-x1+x2=avg
第二个人的金币变化为:
book[2]-x2+x3=avg
所以有:
x2=avg-book[1]+x1;
x3=avg-book[2]+x2=avg-book[2]+avg-book[1]+x1;
我们设:
C1=book[1]-avg;
C2=C1+book[2]-avg;
C3=C2+book[3]-avg;
以此类推:
那么;
x2=x1-C1;
x3=x1-C2;
那么总的移动金币数为:
sum=|x1|+|x2|+…+|xn|=|x1|+|x1-C1|+…+|x1-C(n-1)|;
看似问题解决得差不多了,但是x1是多少呢?
我们要sum最小,通过分析,我们发现x1的值为C的中位数!
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define N 1000005
using namespace std;
long long book[N],val[N];
int main()
{
int n;
while(scanf("%d",&n)==1)
{
long long sum=0;
for(int i=1;i<=n;i++)
{
scanf("%lld",&book[i]);
sum+=book[i];
}
long long avg=sum/n;
val[0]=0;
for(int i=1;i<n;i++)
{
val[i]=val[i-1]+book[i]-avg;
}
sort(val,val+n);
long long cost=0,mid=val[n/2];
for(int i=0;i<n;i++)
{
cost+=abs(val[i]-mid);
}
printf("%lld\n",cost);
}
return 0;
}
财富再分配问题
428





