ja / en
Overview

二分探索

2024/07/29
1 min read

Purpose

Performs binary search.

Time Complexity

O(logn)O(\log n)

Usage

dichotomy(lower_bound, upper_bound, λ:int -> bool lambda) returns the minimum number for which λ is true. The search range is passed as a half-open interval, and if no evaluation is true within the interval, the upper bound is returned. For example

dichotomy(0, 100, [](int n){
return 50 < n;
});

returns 51, which is the minimum n satisfying 50<n50 < n.

Implementation

int dichotomy(int ng, int ok, const function<bool(int)> &discriminant) {
ng--;
while (ok - ng > 1)
(discriminant((ng + ok) / 2) ? ok : ng) = (ng + ok) / 2;
return ok;
}

Verify

https://atcoder.jp/contests/typical-algorithm/submissions/59723946