Official

C - Min Diff Sum Editorial by evima


[1] Preface

The problem does not require advanced knowledge and heavy implementation at all, but starting in the right direction may not be easy.

[2] Solution

Let us look at the maximum among \(L_i\) and minimum among \(R_i\) and let \(L_l=M, R_r=m\). Now, do the following case-by-case analysis.

1. If \(M \leq m\)

Let \(X\) be an integer such that \(M \leq X \leq m\). Since \(M\) is the maximum among \(L_i\), we have \(L_i \leq X\) for all \(i\). Similarly, we have \(X \leq R_i\) for all \(i\). Thus, everyone can stand at coordinate \(X\), for a dissatisfaction level of \(0\).

2. If \(M>m\)

\(M>m\) means \(L_l>R_r\), so we have \(l \neq r\). Now, consider the dissatisfaction level where \(x_l=A\) and \(x_r=B\).

First, one can show that \(B \leq x_i \leq A\) for all \(i\) in an optimal solution.

Proof:

Assume that there is \(i\) such that \(x_i < B\) or \(x_i > A\) in an optimal solution. Since \(B \leq m < M \leq A\), we have \(B \leq R_i\) and \(L_i \leq A\) for all \(i\). Thus, one can reassign \(x_i=B\) for all \(i\) such that \(x_i<B\) and \(x_i=A\) for all \(i\) such that \(x_i>A\) to decrease the dissatisfaction level, which is a contradiction.

Let \(C\) be the sum of the contributions to the dissatisfaction level by pairs of people, none of whom is \(l\) or \(r\). Then, the dissatisfaction level can be represented as:

\( \displaystyle\sum_{i=1}^{N-1}\sum_{j=i+1}^{N}|x_j-x_i| = C + |A-B| +\sum_{i \neq l,r}^{}|x_i-B|+\sum_{i \neq l,r}^{}|A-x_i|\).

By using \(B \leq x_i \leq A\), this can be transformed into:

\(C + (A-B) \times (N-1)\).

To minimize this, one should let \(A=M, B=m\).

By recursively computing \(C\) from the above, the final answer can be found as:

\( \displaystyle\sum_{i=0}^{N-1}\max(0,L_i-R_i)\times(N-2\times i-1)\)

where \(L\) and \(R\) are sorted in descending and ascending order, respectively.

Sample implementation (C++)

#include <bits/stdc++.h>
using namespace std;
int main(){
    int N; cin >> N;
    vector<long long> L(N),R(N);
    for(int i=0;i<N;i++)cin >> L[i] >> R[i];
    sort(L.begin(),L.end(),greater<>());
    sort(R.begin(),R.end());
    long long ans=0;
    for(int i=0;i<N;i++) ans += max(0ll,L[i]-R[i])*(N-2*i-1);
    cout << ans << endl;
}

posted:
last update: