题解 UVA - 11300 Spreading the Wealth

题解 UVA - 11300 Spreading the Wealth

1:题意

A Communist regime is trying to redistribute wealth in a village. They have have decided to sit everyone around a circular table. First, everyone has converted all of their properties to coins of equal value, such that the total number of coins is divisible by the number of people in the village. Finally, each person gives a number of coins to the person on his right and a number coins to the person on his left, such that in the end, everyone has the same number of coins. Given the number of coins of each person, compute the minimum number of coins that must be transferred using this method so that everyone has the same number of coins.

大致意思是:初始n个人围坐成环形,每个人都有 a i a_i ai金币。每个人可以给他的左或右边的人一些金币。要求所有人有相同数量的金币,求最小的转手金币的数量,保证金币的总数可以整除人数。

2:思路:

x i x_i xi为第i个人向右边的人传递的金币数量,若 x i − 1 x_{i-1} xi1为负则表示第i个人向左传递金币。最终结果即为 ∑ ∣ x i ∣ \sum |x_i| xi。很显然,我们知道每个人最终的金币数量为金币的平均数设为m。对于任意一个人而言,他最终的金币数 m = a i + x i − 1 − x i m=a_i+x_{i-1}-x_i m=ai+xi1xi x i = a i + x i − 1 − m x_i=a_i+x_{i-1}-m xi=ai+xi1m每个 x i x_i xi均可以由 x 1 x_1 x1递推求得。结果可表示为 x i = x 1 − c i x_i=x_1-c_i xi=x1ci 所求答案即为 ∑ ∣ x 1 − c i ∣ \sum |x_1-c_i| x1ci 。这个式子的几何意义为在一维坐标轴上点 x 1 x_1 x1到点 c i c_i ci的距离和。我们要最小化这个距离和。那么 x 1 x_1 x1应该取 c i c_i ci的中位数。递推求解 x i x_i xi即可得到答案。

3:代码

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 1e6+7;
long long a[MAXN],c[MAXN];
inline long long Abs(const long long a){
	return a<0?-a:a; 
}
int main(){
	int n;
	while(scanf("%d",&n)==1){
		long long sum=0,ans=0;
		for(int i=1;i<=n;i++){
			scanf("%lld",&a[i]); 
			sum+=a[i];
		}
		long long m=sum/n;
		for(int i=1;i<=n;i++){
			c[i]=c[i-1]+a[i]-m;
		}
		sort(c+1,c+n+1);
		long long x1=c[n/2];
		for(int i=1;i<=n;i++){
			ans+=Abs(c[i]-x1);
		}
		cout<<ans<<'\n';
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值