【題解】糖果傳遞

題目大意

  有\(n\)個小朋友坐成一圈(\(1 \leq n \leq 1000000\)),每人有\(a_i\)個糖果。每人只能給左右兩人傳遞糖果。每人每次傳遞一個糖果代價爲\(1\)。求最小代價。ios

題解

  環形實際上就是\(n\)種鍊形。咱們先考慮第\(1\)\(n\)個小朋友造成鍊形的狀況。
  咱們設
\[s_i = \sum_{j = 1}^{i} (a_i - \overline{a})\]
  則此時對於每一個\(i\),第\(i\)個小朋友傳遞的代價是\(s_i\)
  此時咱們再回到環形,若是咱們在第\(k\)個小朋友處拆成鍊形,則當\(i \geq k\)時,第\(i\)個小朋友傳遞的代價爲
\[| s_i - s_k |\]
  當\(i < k\)時,第\(i\)個小朋友傳遞的代價爲
\[| s_i + s_n - s_k | \]
  根據咱們前面的定義,能夠獲得,\(s_n\)恆爲\(0\)
  因此當\(i < k\)時,第\(i\)個小朋友傳遞的代價也爲
\[| s_i - s_k |\]
  因此總代價爲
\[\sum_{i = 1}^{n} | s_i - s_k |\]
  根據貪心策略,顯然這裏的\(s_k\)應爲\(\{ s_i \}\)中的中位數,排序處理一下便可。git

#include <iostream>
#include <cstdio>
#include <cctype>
#include <algorithm>

#define MAX_N (1000000 + 5)
#define SIZE (1 << 21)

#define abs(x) ((x) >= 0 ? (x) : -(x))
#define Getchar() (p1 == p2 && (p2 = (p1 = fr) + fread(fr, 1, SIZE, stdin), p1 == p2) ? EOF : *p1++)

using namespace std;

char fr[SIZE], * p1 = fr, * p2 = fr;

void Read(int & num)
{
    num = 0;
    char ch = Getchar();
    while (!isdigit(ch)) ch = Getchar();
    while (isdigit(ch)) num = num * 10 + ch - '0', ch = Getchar();
    return;
}

int n;
int a[MAX_N];
int s[MAX_N];
long long ans;

int main()
{
    Read(n);
    long long tmp = 0;
    for (int i = 1; i <= n; ++i)
    {
        Read(a[i]);
        tmp += a[i];
    }
    tmp /= n;
    for (int i = 1; i <= n; ++i)
    {
        s[i] = s[i - 1] + a[i] - tmp;
    }
    sort(s + 1, s + n + 1);
    tmp = s[n >> 1];
    for (int i = 1; i <= n; ++i)
    {
        ans += abs(s[i] - tmp);
    }
    printf("%lld", ans);
    return 0;
}
相關文章
相關標籤/搜索