Spreading the Wealth UVa-11300

来源:互联网 发布:淘宝学历提升是真的吗 编辑:程序博客网 时间:2024/06/05 15:43

题目传送门

题意:这个题题目的意思十分的简单,就是有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 1000000007using 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;}
原创粉丝点击