C++ アルゴリズムとデータ構造のライブラリ
#include "library/search/binary_search/binary_search.hpp"5<=xならL=4, R=5(LRの誤差がEPS内)
L R
x x x o o o o
↑ここを求める
$O(logN)$
auto [L, R] = binary_search([&](long long x){
return 5 <= x;
});
#pragma once
#include <functional>
pair<long long, long long> binary_search(function<bool(long long)> f) {
long long L = 0, R = 1, MID = 0;
while (!f(R)) R <<= 1;
while (abs(R - L) > 1) {
MID = L + (R - L) / 2;
(f(MID) ? R : L) = MID;
}
return {L, R};
}#line 2 "library/search/binary_search/binary_search.hpp"
#include <functional>
pair<long long, long long> binary_search(function<bool(long long)> f) {
long long L = 0, R = 1, MID = 0;
while (!f(R)) R <<= 1;
while (abs(R - L) > 1) {
MID = L + (R - L) / 2;
(f(MID) ? R : L) = MID;
}
return {L, R};
}