Spreading the Wealth(UVa 11300)
来源:互联网 发布:中天证券软件下载 编辑:程序博客网 时间:2024/05/17 06:45
来自《算法竞赛入门经典训练指南》
1.题目原文
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2275
分金币,使得n个人最终金币数均相等。分金币时,每个人都可以给他左边的或者右边的,求被转手的金币数量的最小值。
2.解题思路
假设1号给2号5个金币,2号给1号3个金币,等价于1号给2号2个金币,2号什么也没给1号,因此只需要考虑单向的即可。
令x[i]表示i号给i-1号的金币个数,其中i从2到n,x[1]表示1号给n号的金币个数。
记M为最终每个人的金币个数,A[i]表示每个人最开始的金币个数。
则有
对于第一个人,A[1]-x[1]+x[2]=M→ x[2]=M-A[1]+x[1]=x[1]-C[1]。
对于第二个人,A[2]-x[2[+x[3]=M→ x[3]=M-A[2]+X[2]=2M-A[1]-A[2]+x[1]=x[1]-C[2]。
因此类推,对n个人,A[n]-x[n]+x[1]=M。其实这个式子没用,因为可由前n-1个式子相加得到。
其中C[i]=C[i-1]+A[i]-M。
原题就变成了想让所有的x[i]的绝对值之和最小,即|x[1]|+|x[1]-C[1]|+……+|x[1]-C[n-1]|最小。经典问题,不解释。
3.AC代码
#include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> #include<cmath> #include<bitset> #include<sstream> using namespace std;using namespace std;#define INF 0x7ffffffftypedef long long ll;const int maxn=1e6+10;ll A[maxn],C[maxn],tot,M;int n;int main(){ while(scanf("%lld",&n)!=EOF){ tot=0; for(int i=0;i<n;i++){ scanf("%lld",&A[i]); tot+=A[i]; } M=tot/n; C[0]=0; for(int i=1;i<n;i++){ C[i]=C[i-1]+A[i]-M; } sort(C,C+n); ll x1=C[n/2],ans=0; for(int i=0;i<n;i++){ ans+=fabs(C[i]-x1); } printf("%lld\n",ans); } return 0;}
0 0
- Uva - 11300 - Spreading the Wealth
- uva 11300 - Spreading the Wealth
- Uva-11300-Spreading the Wealth
- UVA 11300 Spreading the Wealth
- UVa 11300 - Spreading the Wealth
- uva 11300 Spreading the Wealth
- UVA 11300 Spreading the Wealth
- uva 11300 Spreading the wealth
- UVA - 11300 Spreading the Wealth
- UVa 11300 Spreading the Wealth
- UVA 11300 Spreading the Wealth
- UVa 11300 Spreading the Wealth
- UVA 11300 Spreading the Wealth
- UVA 11300 - Spreading the Wealth
- UVA - 11300 Spreading the Wealth
- UVA 11300-Spreading the Wealth
- UVA 11300 Spreading the Wealth
- UVA 11300 Spreading the Wealth
- Vsftpd本地nologin用户不能登录FTP解决办法
- argc与argv[]
- apache lighttpd nginx 对比分析
- javaScript相等运算符==
- HDU 5135 Little Zu Chongzhi's Triangles(数学题)
- Spreading the Wealth(UVa 11300)
- set/multiset用法详解
- Picasso之图片缓存机制
- 虚析构函数的作用
- <<改善既有代码的设计>> 第2章
- Go基础语法(一)
- JS实现各种复制到剪贴板
- 高阶函数
- Java 16进制字符串转化成十六进制数字