我们令$x_i$表示第$i$个人传递给第$i + 1$个人的糖果数量,那么有:
$$x_n - x_1 = \overline{a} - a_1$$
$$x_1 - x_2 = \overline{a} - a_2$$
$$\cdots$$
$$x_{n - 1} - x_n = \overline{a} - a_n$$
那么求等式两边求前缀和有:
$$x_n - x_i = \sum\limits_{j = 1}^i \overline{a} - a_j$$
移项有:
$$x_i = x_n - (\sum\limits_{j = 1}^i \overline{a} - a_j)$$
我们发现答案等于:
$$ans = \sum\limits_{i = 1}^n |x_i| = \sum\limits_{i = 1}^n (x_n - \sum\limits_{j = 1}^i \overline{a} - a_j)$$
我们令$s_i = \sum\limits_{j = 1}^i \overline{a} - a_j$
我们发现$x_n$的取值最大为所有$a_i$之和
那么易得,$x_n$取值为$s_i$的中位数答案最优
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 #define ll long long 5 #define N 1000010 6 int n; 7 ll a[N]; 8 9 void Run() 10 { 11 while (scanf("%d", &n) != EOF) 12 { 13 ll sum = 0; 14 for (int i = 1; i <= n; ++i) 15 scanf("%lld", a + i), sum += a[i]; 16 sum /= n; 17 for (int i = 1; i <= n; ++i) 18 { 19 ll t = sum - a[i]; 20 a[i] = a[i - 1] + t; 21 } 22 sort(a + 1, a + 1 + n); 23 ll t = a[n / 2]; 24 ll ans = 0; 25 for (int i = 1; i <= n; ++i) 26 ans += abs(t - a[i]); 27 printf("%lld\n", ans); 28 } 29 } 30 31 int main() 32 { 33 #ifdef LOCAL 34 freopen("Test.in", "r", stdin); 35 #endif 36 37 Run(); 38 return 0; 39 }