P2125: Books on the Library Shelf — Solution
Approach
This problem is a good one for mathematical reasoning.
We consider treating every move as a one-way move, and let \(x_i\) be the number of books moved from \(i\) to \(i - 1\). Obviously, if we want to move books to the right, we just subtract the corresponding amount from \(x_{i + 1}\).
Next comes the reasoning. Consider that the total answer is: \(\sum_{i = 1}^n |x_i|\). We want to minimize this thing. To simplify this thing, we can notice the recurrence property hidden in \(x_i\):
\[ \begin{cases} a_1 = avg - x_2 + x_1 \\ a_2 = avg - x_3 + x_2 \\ \dots \end{cases} \]
We can fix \(x_1\) as a constant, then move terms across and substitute:
\[ \begin{gathered} x_2 = avg - a_1 + x_1 \\ x_3 = avg - a_2 + x_2 = 2avg - a_2 - a_1 + x_1 = x_1 - (a_1 + a_2 - 2avg) \\ x_n = x_1 - (\sum_{i = 1}^{n - 1} a_i - (n - 1) \times avg) \end{gathered} \]
Notice that the sum at the end can be computed by recurrence (\(c_i = c_{i - 1} + a_i - avg\)), and now it becomes:
\[\sum_{i = 1}^n |x_i| = |x_1 - c_1| + |x_1 - c_2| \dots \]
Warehouse Location, then reconstruct the answer and that is it.
Code
// P2125.cpp
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int MAX_N = 5001001;
ll sum, ai[MAX_N], n, ci[MAX_N], x1, org[MAX_N];
int main()
{
scanf("%lld", &n);
for (int i = 1; i <= n; i++)
scanf("%lld", &ai[i]), sum += ai[i];
sum /= n;
for (int i = 1; i <= n; i++)
ci[i] = org[i] = ci[i - 1] + ai[i] - sum;
nth_element(ci + 1, ci + (n >> 1) + 1, ci + 1 + n), x1 = ci[(n >> 1) + 1];
ll ans = 0;
for (int i = 1; i <= n; i++)
ans += llabs(ci[i] - x1);
printf("%lld\n", ans);
for (int i = 1; i < n; i++)
printf("%lld %lld\n", x1 - org[i - 1], -(x1 - org[i]));
printf("%lld %lld\n", x1 - org[n - 1], -x1);
return 0;
}