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;
}


 

 

posted on 2013-12-03 12:31  我的小人生  阅读(136)  评论(0编辑  收藏  举报