UVa11300 Spreading the Wealth(数学问题)

本文介绍了一种算法,用于解决一群人如何通过最小金币转移达到每人金币数相同的问题。通过计算最终每人应有的金币数,并利用中位数特性,找到最优的金币转移方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出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_JUDGE
	ifstream fin("f:\\OJ\\uva_in.txt");
	streambuf *old = cin.rdbuf(fin.rdbuf());
#endif
	
	int 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_JUDGE
	cin.rdbuf(old);
#endif
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值