templates/binary-search-on-answer.cpp
compilable
$cat templates/binary-search-on-answer
Binary Search on Answer
Search for the optimal value satisfying a monotonic predicate in O(log n).
#binary-search#predicate#optimization#monotonic
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
bool check(ll mid) {
// return true if mid is a feasible answer
return true;
}
ll bsOnAnswer(ll lo, ll hi) {
ll ans = -1;
while (lo <= hi) {
ll mid = lo + (hi - lo) / 2;
if (check(mid)) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}22 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Binary Search on Answer
Applies binary search to optimization problems with a monotonic predicate : if is true, then is true for all (or vice versa).
How It Works
check(mid) function that returns true if mid is a feasible answercheck(mid) passes, move the boundary inward; otherwise, move outwardTemplate
check(x) is true → hi = midcheck(x) is true → lo = mid