uva 11300 - Spreading the Wealth(数论)

题目链接:uva 11300 - Spreading the Wealth


题目大意:有n个人坐在圆桌旁,每个人有一定的金币,金币的总数可以被n整除,现在每个人可以给左右的人一些金币,使得每个人手上的金币数量相等,问说最少移动的金币数额。


解题思路:假设xi为第i个人给左手边人的金币数量,那么就有a[i] - x[i]+ x[i + 1] = aver.那么

a[1] - x[1] + x[2] = aver -> x2 = aver - a[1] + x[1]  -> x[2]= x[1] - c[1]  (c[i]为∑a[j] - aver)

a[2] - x[2] + x[3] = aver -> x3 = aver - a[2] + x[2] = aver - a[2] + aver - a[1] + x[1] = x[1] - c[2]

.....

所以就有a[n] = x[1] - c[n],然后∑|x[i]| = ∑ | x[1] - c[i] |, 然后就可以转化成在数轴选取点x[1] 到点0 , c[1] ....c[n - 1],使得距离最小,(x[1] - c[n])即为x[1]到0的距离。然后就是最取中位数计算距离。


 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>

using namespace std;
#define ll long long

const int N = 1000005;

ll n, aver, a[N], c[N];

void input() {
	ll sum = 0;
	for (int i = 1; i <= n; i++) {
		scanf("%lld", &a[i]);
		sum += a[i];
	}

	aver = sum / n;
	c[0] = 0;
	for (int i = 1; i < n; i++)
		c[i] = c[i - 1] - a[i] + aver;
	sort(c, c + n);
}

ll solve() {
	ll tmp = c[n / 2], ans = 0;

	for (int i = 0; i < n; i++)
		ans += abs(c[i] - tmp);
	return ans;
}

int main () {

	while (scanf("%lld", &n) == 1) {
		input();
		printf("%lld\n", solve());
	} 
	return 0;
}


 

 

转载于:https://www.cnblogs.com/fuhaots2009/p/3455585.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值