算法 UVA 11300

例3:题目描述

圆桌旁边坐着n个人,每个人有一定数量的金币,金币的总数能被n整除。每个人可以给他左右相邻的人一些金币,最终使得每个人的金币数量相等。您的任务是求出被转手的金币的数量的最小值。

 

输入格式

输入包含多组数据。每组数据第一行为一个整数n(n<=1000000),以下n行每行为一个整数,按逆时针顺序给出每个人拥有的金币数。输入结束标志为文件结束符(EOF).

 

输出格式

对于每组数据,输出被转手的金币的数量的最小值

输入样例

3
100
100
100
4
1
2
5
4

输出样例

0
4

//2019.4.20 分金币
#include <iostream>
#include <algorithm>
using namespace std;

const int maxn = 1000000 + 10;
long long A[maxn], C[maxn], tot, M;

int main()
{
    int n;
    while (scanf_s("%d", &n) == 1)
    {
        tot = 0;
        for (int i = 1; i <= n; i++)
        {
            scanf_s("%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]);//?
        }
        cout << ans;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/cjwen/p/10741637.html