uva 11300 Spreading the wealth
来源:互联网 发布:常州地球人软件 编辑:程序博客网 时间:2024/05/17 07:22
题目链接:点击打开链接
题目大意:圆桌旁坐着n个人,每个人有一定数量的金币,金币总数能被n整除.每个人需要给相邻的人一些金币,使得最后每个人手中的金币数目一样.你需要求出转手金币数量的最小值.
思路:数学分析 转化为求数轴上到n个点距离总和最小的点
分析:设每个人开始有Ai个金币.每个人最终拥有的金币数设为M.设xi为第i个人给第i-1个人的金币数(x1表示第1个人给第n个人的金币数).那么可以列出下列方程:
对于第一个人: A1-x1+x2 = M -> x2 = x1-(A1-M) = x1 - C1(设C1 = A1 - M,下面类似)
对于第二个人: A2-x2+x3 = M -> x3 = x2-(A2-M) = x1 - C1 - (A2 - M) = x1 - C2
对于第三个人: A3-x3+x4 = M -> x4 = x3-(A3-M) = x1 - C1 - C2 - (A3 - M) = x1 - C3
...
最后,相当于求|x1| + |x1-C1| + |x1-C2| + |x1-C3| +... + |x1-Cn-1|的最小值,转化为求数轴上到n个点(C1,C2,C3...)距离总和最小的点,即这些点的中位数.
代码:
#include <cstdio>#include <algorithm>#include <cmath>using namespace std;const int maxn = 1000001 + 5;long long coins[maxn];long long coin_diff[maxn];int main(){int n;long long sum, average;int i;while (scanf("%d", &n) != EOF){sum = 0;for (i = 0; i < n; i++) {scanf("%lld", &coins[i]);sum += coins[i];}average = sum / n;long long temp = 0;coin_diff[0] = 0;for (i = 1; i < n; i++) {temp += coins[i-1];coin_diff[i] = temp - average * i;}sort(coin_diff, coin_diff + n);long long middle = coin_diff[n / 2];sum = 0;for (i = 0; i < n; i++)sum += abs(middle - coin_diff[i]);printf("%lld\n", sum);}return 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
- 触发器做审计、系统触发器简单介绍
- Mingw下编译PJSIP时报错undefined reference to `pjmedia_format_init_audio'问题解决
- 中文字符串排序解决方案
- iOS - 制作真机静态库:
- 程序员的成长历程,30岁以内的程序员请勿好大喜功!
- uva 11300 Spreading the wealth
- mipi介绍
- Xamarin Mono For Android 4.6.00049
- 一个简单的makefile示例及其注释
- linux下DMA API
- qeephp数据库关联操作
- 推荐八个配色网站
- JQuery Highcharts 动态图表生成方法
- C#正则截取URL网址字符串