UVA - 11300 Spreading the Wealth (formula derivation)

Description

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

Analysis of ideas:

  Since the total number of coins than the total number of people on an integer, we use m to represent the number, that is, after multiple points finish coins, everyone has m coins hands, we use an array to represent A

每个人在分硬币之前的每个人的硬币数,用x数组来表示第i个人给他前一个人的硬币数,那么就有A[i]-x[i]+x[i+1]=m,即x[i+1]=x[i]-A[i]+m;

将xi往后推则有:

x2=x1-A[i]+m;
x3=x2-A2+m=x1-A[1]-A[2]+2*m;
x4=x3-A3+m=x1-A[1]-A[2]-A[3]+3*m;
于是我们为了简化这些式子,用C[1]=A[1]-m,C[2]=c[1]+A[2]-m ··· ···
则有

x2=x1-C[1];
x3=x1-C[2];
x4=x1-C[3];
···
我们最终要求的就是|x1|+|x1-C1|+|x1-C2|+···+|x1-Cn-1|最小,则我们取得x1应该为ci的中位数,最终统计答案即可。

开long long

附上代码:

 

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int N=1e6+10;
 6 long long a[N],c[N],m,n,sum;
 7 int main(){
 8     while(scanf("%lld",&n)==1){
 9         memset(a,0,sizeof(a));
10         memset(c,0,sizeof(c));
11         sum=0;       //用于计算sum 
12         for(int i=1;i<=n;++i){
13             scanf("%lld",&a[i]);
14             sum+=a[i];
15         }
16         m=sum/n;
17         for(int i=1;i<=n;++i)
18             c[i]=c[i-1]+a[i]-m; //由前面的公式得到 
19         sort(c+1,c+n+1);
20         long long x1=c[n/2],ans=0; //x1取c[]的中位数 
21         for(int i=1;i<=n;++i)
22             ans+=abs(x1-c[i]);//统计答案. 
23         printf("%lld\n",ans);
24     }
25     return 0;
26 }

 

Guess you like

Origin www.cnblogs.com/li-jia-hao/p/12663607.html