serna37's Library

Logo

C++ アルゴリズムとデータ構造のライブラリ

View the Project on GitHub serna37/library-cpp

:heavy_check_mark: 整数上の二分探索
(library/search/binary_search/binary_search.hpp)

整数上の二分探索

できること

計算量

$O(logN)$

使い方

auto [L, R] = binary_search([&](long long x){
    return 5 <= x;
});

Verified with

Code

#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};
}
Back to top page