Problem solution · C++

ABC416 D — Match, Mod, Minimize 2

ABC416 D — Match, Mod, Minimize 2: a C++ solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to michimani AtCoder Solutions.

Technique
Binary search
Source
michimani AtCoder Solutions
Length
63 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For ABC416 D — Match, Mod, Minimize 2, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 63 lines of C++ from the credited upstream file abc416_d.cpp.
  • The implementation visibly relies on sequence storage.
  • 4 loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from michimani AtCoder Solutions by michimani and is used under the MIT licence.

Full codeABC416 D — Match, Mod, Minimize 2 · C++C++
Use this to learn the idea, then write your own version.
#include <algorithm>#include <iostream>#include <set>#include <vector> using namespace std;using ui = unsigned int;using ll = long long; int main() {    ui t;    cin >> t;     for (; t--;) {        ui n;        ll m;        cin >> n >> m;         vector<ll> a(n), b(n);        for (ui i = 0; i < n; i++) cin >> a[i];        for (ui i = 0; i < n; i++) cin >> b[i];         sort(a.begin(), a.end());        sort(b.begin(), b.end());         ll total = 0;        multiset<ll> available(a.begin(), a.end());         for (ui i = 0; i < n; i++) {            ll bi = b[i];            ll target = m - bi;             auto it = available.lower_bound(target);            ll best_val = (bi + *available.begin()) % m;            auto best_it = available.begin();             if (it != available.end()) {                ll val = (bi + *it) % m;                if (val < best_val) {                    best_val = val;                    best_it = it;                }            }             if (it != available.begin()) {                --it;                ll val = (bi + *it) % m;                if (val < best_val) {                    best_val = val;                    best_it = it;                }            }             total += best_val;            available.erase(best_it);        }         cout << total << endl;    }     return 0;} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗