UVa - 11300 Spreading the Wealth (代数分析)

https://vjudge.net/problem/UVA-11300

训练指南 1 - 3

题意:圆桌有n个人,每个人都有一定的金币,金币总数能被n整除,每个人可以给相邻的人一些金币,使得他们每个人的金币相等。求转手金币的最小值。

解决:书上给了一大串代数分析,很好,不再赘述。以后做题可以先列公式,可能会有意想不到的事情发生(简单不知道多少倍)。

细节:分析到最后,有一个中位数的应用,一个点到多个点的距离加和,这个点在这些数的中位数处,和最小。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 1000000;

int n;
long long a[maxn + 5], c[maxn + 5], tot, m;

int main(){
    while(scanf("%d", &n) != EOF){
        tot = 0;
        for(int i = 0; i < n; i++){
            scanf("%lld", &a[i]);
            tot += a[i];
        }
        m = tot / n;
        c[0] = 0;
        for(int i = 1; i < n; i++){
            c[i] = c[i-1] + a[i] -m;
        }

        sort(c, c+n);
        long long x1 = c[n/2], ans = 0;
        for(int i = 0; i < n; i++) { ans += abs(x1 - c[i]);}

        printf("%lld\n", ans);
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值