UVa11300 Spreading the Wealth(数学问题)
来源:互联网 发布:大数据体系 编辑:程序博客网 时间:2024/06/05 11:14
题意:给出n个人,每个人有一些金币,可以给一些金币左边或者右边的人,最终使得每个人有相同的金币,问最小的转移金币是多少?
思路:可以假定给金币方向是逆时间方向,值可能是正负。M表示最终每个人有的金币,用xi表示第i个人所给的,Pi表示第i个人有的金币
有M = P1 - x1 + x2 => x2 = x1 - (P1 - M) => x2 = x1 - c1
P2 - x2 + x3 = M => x3 = x1 - (P1 + P2 - 2M) => x3 = x1 - c2;
Pn-1 - xn-1 + xn = M => xn = x1 - (P1+P2+...+Pn-1 - (n-1)M) => xn = x1 - cn-1
则总的转移次数为sum = |x1|+|x1-c1|+...+|x1-cn-1|是最小值,转变为数学问题0,c1,c2,cn-1这几个点构成的数轴上,找出一个点,使得到这几个点的和最小,显然是中位点
代码如下:
#include <iostream>#include <fstream>#include <algorithm>#include <vector>using namespace std;typedef unsigned long long ULL;class SpreadingTheWealth{public:ULL spreadTheWealth(vector<ULL> v){vector<int> c(v.size());ULL sum = 0;for (size_t i = 0; i < v.size(); i++) sum += v[i];ULL m = sum / v.size();c[0] = 0;for (size_t i = 1; i < c.size(); i++){c[i] = c[i - 1] + v[i - 1] - m;}sort(c.begin(), c.end());ULL ans = 0;ULL x = c[c.size() / 2];for (size_t i = 0; i < v.size(); i++){ans += labs(c[i] - x);}return ans;}};SpreadingTheWealth solver;int main(){#ifndef ONLINE_JUDGEifstream fin("f:\\OJ\\uva_in.txt");streambuf *old = cin.rdbuf(fin.rdbuf());#endifint n;while (cin >> n){vector<ULL> v;for (int i = 0; i < n; i++){ULL coin;cin >> coin;v.push_back(coin);}cout << solver.spreadTheWealth(v) << endl;}#ifndef ONLINE_JUDGEcin.rdbuf(old);#endifreturn 0;}
阅读全文
0 0
- UVa11300 Spreading the Wealth(数学问题)
- UVA11300 Spreading the Wealth (数学推导+中位数)
- UVA11300:Spreading the Wealth
- UVA11300 Spreading the Wealth
- uva11300 Spreading the Wealth
- Uva11300 - Spreading the Wealth
- UVa11300 - Spreading the Wealth
- Uva11300 - Spreading the Wealth
- uva11300 Spreading the Wealth
- UVA11300:Spreading the Wealth
- UVA11300:Spreading the Wealth
- uva11300 - Spreading the Wealth (中位数)
- uva11300 - Spreading the Wealth(分金币)
- UVa11300 - Spreading the Wealth (分金币)
- [UVA11300][智商题]Spreading the Wealth
- UVA11300——Spreading the Wealth (贪心+建模)
- uva 11300Spreading the Wealth(数学 中位数)
- UVA 11300 Spreading the Wealth(数学)
- 史上最全的常用事件:移动端事件及PC端:鼠标/键盘/表单事件
- poj2653:Pick-up sticks(链表)
- windows平台下载并编译webrtc代码(代理)2017.11.17
- 欢迎使用CSDN-markdown编辑器
- X
- UVa11300 Spreading the Wealth(数学问题)
- android 安卓保存图片到手机相册并且解决图片发黄问题
- 递推之猴子爬山
- css实现垂直水平居中的5种方法
- D
- 031 矩阵关系专题之等价、相似、合同(线性代数系列结束)
- Gephi初识之简单绘图学习
- 分布式session跨域的两种实现方式
- 简述指针数组 数组指针 函数指针 函数指针数组和函数指针数组的指针