---
id: 1823
lang: en
translation_of: index.md
source_sha256: cdb55c0422f85d7165562a7268c7383c3892520e48b688520daceae2acebcc2a
title: "P2125: Books on the Library Shelf — Solution"
description: "This problem is a good one for mathematical reasoning."
tags: []
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 图书馆书架上的书 rendered literally as “Books on the Library Shelf”."
---

## 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}$.

<!--more-->

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
$$

<span class="slang" data-zh="货仓选址" data-gloss="huòcāng xuǎnzhǐ, “choosing a warehouse site”. A classic textbook problem: place a warehouse so the total distance to all stores is minimal.">Warehouse Location</span>, then reconstruct the answer and that is it.

## Code

```cpp
// 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;
}
```
