ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2020-04-08 22:53:38  阅读:244  来源: 互联网

标签:Wealth 硬币 Spreading coins number long person 11300 x1


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 }

 

标签:Wealth,硬币,Spreading,coins,number,long,person,11300,x1
来源: https://www.cnblogs.com/li-jia-hao/p/12663607.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有