Problem
A * 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. 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.
The 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
Problem setter: Josh Bao
题目大意:n人围绕圆桌,每个人有一定数量金币,金币总数能被n整除。每个人可以给他左右的人一些金币,最终使每个人金币数相等。求被转手金币最小值。
解题思路:
1、列出方程组:
设Ai为初始金币数,xi表示i号给i-1号金币数[可正可负],M为最终每个人的金币数,则:
for the first person: A1-x1+x2=M-->x2=M-A1+x1=x1-C1[规定C1=A1-M]
for the second person: A2-x2+x3=M-->x3=M-A2+x2=2M-A1-A2+x1=x1-C2
for the third person: A3-x3+x4=M-->x4=M-A3+x3=3M-A1-A2-A3+x1=x1-C3
......
for the nth person: An-xn+x1=M[这是一个多余的式子,并不能给我们更多的信息]
2、转换为单变量问题:
我们希望所有xi的绝对值之和最小,即:|x1|+|x1-C1|+|x1-C2|+...+|x1-Cn|最小。
3、转换为几何问题:
注意上式的几何意义就是数轴上给定n个点找出一个到他们之和尽量小的点。
4、递归求最优解:
这个最优的x1就是他们的中位数。
#include<iostream>
#include<algorithm>
#include<cstdio>
typedef long long LL;
using namespace std;
LL A[],C[];//A[i]表示第i人初始金币数
int main(){
int n;
while(cin>>n){
LL tot=;//总数
for(int i=;i<n;i++){
cin>>A[i];
tot+=A[i];
}
LL M=tot/n;//平均数
C[]=;
for(int i=;i<n;i++){
C[i]=C[i-]+A[i]-M;//递推数组C
}
sort(C,C+n);
LL x1=C[n/],ans=;//计算x1
for(int i=;i<n;i++){
ans+=abs(x1-C[i]);
}
cout<<ans<<'\n';
}return ;
}