UVA – 11300 Spreading the Wealth(公式推导)

UVA – 11300 Spreading the Wealth(公式推导)DescriptionACommunistregimeistryingtoredistributewealthinavillage.Theyhavehavedecidedtositeveryonearoundacirculartable.First,eve

大家好,欢迎来到IT知识分享网。UVA

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

思路分析:

  由于硬币总数比上总人数是一个整数,我们用m来表示这个数,即在多次分完硬币之后,每个人手中都有m个硬币,我们用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 }

 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/34344.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信