AcWing 糖果传递

AcWing 糖果传递

Description

  • 有n个小朋友坐成一圈,每人有a[i]个糖果。

    每人只能给左右两人传递糖果。

    每人每次传递一个糖果代价为1。

    求使所有人获得均等糖果的最小代价。

Input

  • 第一行输入一个正整数n,表示小朋友的个数。

    接下来n行,每行一个整数a[i],表示第i个小朋友初始得到的糖果的颗数。

Output

  • 输出一个整数,表示最小代价。

Sample Input

4
1
2
5
4

Sample Output

4

Data Size

  • 1≤n≤1000000

题解:

  • 贪心(环形均分纸牌)
  • 类似的题以前证明过了,转链接
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#define N 1000005
#define int long long
using namespace std;

int n, avg, ans;
int a[N], c[N];

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

signed main()
{
    cin >> n;
    for(int i = 1; i  <= n; i++) a[i] = read(), avg += a[i];
    avg /= n;
    for(int i = 1; i <= n; i++)
    {
        a[i] -= avg;
        c[i] = c[i - 1] + a[i];
    }
    sort(c + 1, c + 1 + n);
    int mid = n % 2 == 0 ? n / 2 : n / 2 + 1;
    for(int i = 1; i <= n; i++) ans += abs(c[i] - c[mid]);
    cout << ans;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/BigYellowDog/p/11300655.html