Spreading the Wealth UVa-11300

题目传送门

题意:这个题题目的意思十分的简单,就是有n个人围成一圈坐下,每个人一开始都有一定数量的金币,每个人的金币只能给自己身边的两个人,问最少要交换多少次金币才能让每一个人手中的金币数量相等。

思路:这个题目一看到题目感觉不是很复杂,觉得其中应该有一定的数学关系,但是推了一会并没有得出答案,只想到了一个距离的关系。书上这个题目给出的方法十分的好,之前也没有见过这个方法。
假设对所有的人进行从1到n进行编号,第1个人给第n个人x1枚金币,给第2个人x2金币,第二个人给第一个人-x2枚金币,给第三个人x3枚金币……..
从这个方面我们可以得到一个公式
A1 - x1 + x2 = M -> x2 = M - A1 + x2 = x1 - C1(规定C1 = A1 - M)
A2 - x2 + x3 = M -> x3 = M - A2 + x2 = 2M - A1 - A2 + x1 = x1 - C2
……
所有的交换金币次数为x1到xn的绝对值的和
找到中位数即可求的最小值

//
//  main.cpp
//
//  Created by 尹贯宇 on 2017/6/27.
//  Copyright © 2017年 尹贯宇. All rights reserved.
//

#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <set>

#define LL long long
#define MAXN 1000010
#define INF 1000000
#define MOD 1000000007

using namespace std;

LL arr[MAXN];
LL c[MAXN];

int main() {
    ios::sync_with_stdio(false);
    LL n;
    while (cin >> n) {
        LL sum = 0;
        for (int i = 1; i <= n; ++i) {
            cin >> arr[i];
            sum += arr[i];
        }
        LL num = sum / n;
        c[0] = 0;
        for (int i = 1; i < n; ++i) {
            c[i] = c[i - 1] + arr[i] - num;
        }
        sort(c, c + n);
        LL x1 = c[n / 2];
        LL ans = 0;
        for (int i = 0; i < n; ++i)
            ans += abs(x1 - c[i]);
        cout << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值