Official

B - Minimize Abs 1 Editorial by en_translator


Let us find the answer for \(A_i\) by casework.

  • If \(A_i\) is between \(L\) and \(R\), the answer is \(A_i\).

  • If \(A_i\) is less than \(L\), the answer is \(L\).

  • If \(A_i\) is greater than \(R\), the answer is \(R\).

All that left is to implement this using an if statement, and you can get AC (accepted).

We also mention an approach without an if statement. The sought value can be represented as \(\min{(\max{(L,A_i)},R)}\). Most languages max and min functions, enabling us simpler implementation.

Moreover, in C++ the function \(\min{(\max{(L,A_i)},R)}\) itself is provided in the standard library: you can use std::clamp(A_i,L,R).

Sample code (C++):

#include <bits/stdc++.h>
using namespace std;

#define rep(i, x) for(int i = 0; i < (x); i++)

int main() {
    int n, l, r;
    cin >> n >> l >> r;
    vector<int> a(n);
    rep(i, n) cin >> a[i];
    rep(i, n) cout << clamp(a[i], l, r) << " \n"[i == n - 1];
}

posted:
last update: