UVa11300 Spreading the Wealth(数学问题)

题意:给出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 
#include 
#include 
#include 

using namespace std;

typedef unsigned long long ULL;

class SpreadingTheWealth
{
public:
	ULL spreadTheWealth(vector v)
	{
		vector 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 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;
}




你可能感兴趣的:(训练指南,OJ)