m1une's library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:heavy_check_mark: verify/algo/search/golden_section_search.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"

#include <cassert>
#include <cmath>
#include "../../../utilities/fast_io.hpp"
#include <random>
#include <vector>

#include "../../../algo/search/golden_section_search.hpp"

template <class F>
int naive_argmin(int left, int right, F f) {
    int best = left;
    auto best_value = f(best);
    for (int x = left + 1; x < right; ++x) {
        auto value = f(x);
        if (value < best_value) {
            best = x;
            best_value = value;
        }
    }
    return best;
}

template <class F>
int naive_argmax(int left, int right, F f) {
    int best = left;
    auto best_value = f(best);
    for (int x = left + 1; x < right; ++x) {
        auto value = f(x);
        if (best_value < value) {
            best = x;
            best_value = value;
        }
    }
    return best;
}

void test_integer_argmin() {
    auto convex = [](long long x) {
        return (x - 7) * (x - 7) + 3;
    };
    assert(m1une::algo::golden_section_search_argmin<long long>(-100, 101, convex) == 7);

    auto plateau = [](int x) {
        if (x < 3) return 3 - x;
        if (5 < x) return x - 5;
        return 0;
    };
    assert(m1une::algo::golden_section_search_argmin<int>(-10, 10, plateau) == 3);

    auto increasing = [](int x) {
        return x;
    };
    assert(m1une::algo::golden_section_search_argmin<int>(-7, 9, increasing) == -7);
}

void test_integer_argmax() {
    auto concave = [](int x) {
        return -(x + 2) * (x + 2) + 10;
    };
    assert(m1une::algo::golden_section_search_argmax<int>(-20, 20, concave) == -2);

    auto plateau = [](int x) {
        if (x < -4) return x + 4;
        if (1 < x) return 1 - x;
        return 0;
    };
    assert(m1une::algo::golden_section_search_argmax<int>(-20, 20, plateau) == -4);

    auto increasing = [](int x) {
        return x;
    };
    assert(m1une::algo::golden_section_search_argmax<int>(-7, 9, increasing) == 8);
}

void test_random_integer_arrays() {
    std::mt19937_64 rng(20260709);
    for (int tc = 0; tc < 1000; ++tc) {
        int n = static_cast<int>(rng() % 200) + 1;
        int low = static_cast<int>(rng() % n);
        int high = low + static_cast<int>(rng() % (n - low));

        std::vector<long long> min_values(n);
        long long value = 0;
        for (int i = low - 1; i >= 0; --i) {
            value += static_cast<long long>(rng() % 7) + 1;
            min_values[i] = value;
        }
        value = 0;
        for (int i = high + 1; i < n; ++i) {
            value += static_cast<long long>(rng() % 7) + 1;
            min_values[i] = value;
        }

        int base = static_cast<int>(rng() % 1000) - 500;
        auto min_f = [&](int x) {
            return min_values[x - base];
        };
        int xmin = m1une::algo::golden_section_search_argmin<int>(base, base + n, min_f);
        assert(xmin == naive_argmin(base, base + n, min_f));

        std::vector<long long> max_values(n);
        for (int i = 0; i < n; ++i) max_values[i] = -min_values[i];
        auto max_f = [&](int x) {
            return max_values[x - base];
        };
        int xmax = m1une::algo::golden_section_search_argmax<int>(base, base + n, max_f);
        assert(xmax == naive_argmax(base, base + n, max_f));
    }
}

void test_integer_evaluation_reuse() {
    for (int n = 1; n <= 300; ++n) {
        int base = -n / 2;
        int center = base + n / 3;
        auto value_at = [center](int x) {
            return x < center ? center - x : x - center;
        };

        std::vector<int> count(n);
        auto f = [&](int x) {
            int index = x - base;
            assert(count[index] == 0);
            ++count[index];
            return value_at(x);
        };

        int xmin = m1une::algo::golden_section_search_argmin<int>(base, base + n, f);
        assert(xmin == naive_argmin(base, base + n, value_at));

        std::fill(count.begin(), count.end(), 0);
        auto g = [&](int x) {
            int index = x - base;
            assert(count[index] == 0);
            ++count[index];
            return -value_at(x);
        };
        auto max_value_at = [&](int x) {
            return -value_at(x);
        };

        int xmax = m1une::algo::golden_section_search_argmax<int>(base, base + n, g);
        assert(xmax == naive_argmax(base, base + n, max_value_at));
    }
}

void test_real_argmin() {
    auto convex = [](double x) {
        return (x - 2.75) * (x - 2.75);
    };
    double x = m1une::algo::golden_section_search_argmin(-100.0, 100.0, convex);
    assert(std::abs(x - 2.75) < 1e-9);

    auto increasing = [](double x) {
        return x;
    };
    double left = m1une::algo::golden_section_search_argmin(-3.0, 8.0, increasing);
    assert(std::abs(left + 3.0) < 1e-9);
}

void test_real_argmax() {
    auto concave = [](double x) {
        return -(x + 0.5) * (x + 0.5);
    };
    double x = m1une::algo::golden_section_search_argmax(-100.0, 100.0, concave);
    assert(std::abs(x + 0.5) < 1e-9);

    auto increasing = [](double x) {
        return x;
    };
    double right = m1une::algo::golden_section_search_argmax(-3.0, 8.0, increasing);
    assert(std::abs(right - 8.0) < 1e-9);
}

void test_evaluation_count() {
    int zero_iteration_calls = 0;
    auto f0 = [&](double x) {
        ++zero_iteration_calls;
        return x * x;
    };
    double midpoint = m1une::algo::golden_section_search_argmin(-2.0, 4.0, f0, 0);
    assert(midpoint == 1.0);
    assert(zero_iteration_calls == 0);

    int calls = 0;
    auto f = [&](double x) {
        ++calls;
        return (x - 1.0) * (x - 1.0);
    };
    m1une::algo::golden_section_search_argmin(-5.0, 5.0, f, 37);
    assert(calls == 38);
}

void test_random_quadratics() {
    std::mt19937_64 rng(20260708);
    std::uniform_real_distribution<double> center_dist(-1000.0, 1000.0);
    std::uniform_real_distribution<double> width_dist(0.1, 1000.0);
    std::uniform_real_distribution<double> coef_dist(0.1, 10.0);

    for (int tc = 0; tc < 1000; ++tc) {
        double center = center_dist(rng);
        double left_width = width_dist(rng);
        double right_width = width_dist(rng);
        double coef = coef_dist(rng);
        double left = center - left_width;
        double right = center + right_width;

        auto convex = [=](double x) {
            double dx = x - center;
            return coef * dx * dx;
        };
        double expected_min = center;
        double xmin = m1une::algo::golden_section_search_argmin(left, right, convex, 120);
        assert(std::abs(xmin - expected_min) < 1e-8);

        auto concave = [=](double x) {
            double dx = x - center;
            return -coef * dx * dx;
        };
        double expected_max = center;
        double xmax = m1une::algo::golden_section_search_argmax(left, right, concave, 120);
        assert(std::abs(xmax - expected_max) < 1e-8);
    }
}

int main() {
    m1une::utilities::FastInput fast_input;
    m1une::utilities::FastOutput fast_output;

    test_integer_argmin();
    test_integer_argmax();
    test_random_integer_arrays();
    test_integer_evaluation_reuse();
    test_real_argmin();
    test_real_argmax();
    test_evaluation_count();
    test_random_quadratics();

    long long a, b;
    fast_input >> a >> b;
    fast_output << a + b << '\n';
}
#line 1 "verify/algo/search/golden_section_search.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"

#include <cassert>
#include <cmath>
#line 1 "utilities/fast_io.hpp"



#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <string>
#include <sys/stat.h>
#include <type_traits>
#include <utility>
#include <unistd.h>
#include <vector>

namespace m1une {
namespace utilities {

struct FastOutput;

namespace internal {

// Shared with the convenience helpers in template.hpp.
inline FastOutput* standard_output_instance = nullptr;

// Detect std::begin(x), std::end(x).
template <class T, class = void>
struct is_range : std::false_type {};

template <class T>
struct is_range<T, std::void_t<
    decltype(std::begin(std::declval<T&>())),
    decltype(std::end(std::declval<T&>()))
>> : std::true_type {};

template <class T>
inline constexpr bool is_range_v = is_range<T>::value;

template <class T>
using range_reference_t = decltype(*std::begin(std::declval<T&>()));

template <class T>
using range_value_t = std::remove_cv_t<std::remove_reference_t<range_reference_t<T>>>;

template <class T, class = void>
struct range_stored_value {
    using type = range_value_t<T>;
};

template <class T>
struct range_stored_value<T, std::void_t<typename std::remove_cv_t<std::remove_reference_t<T>>::value_type>> {
    using type = typename std::remove_cv_t<std::remove_reference_t<T>>::value_type;
};

template <class T>
using range_stored_value_t = typename range_stored_value<T>::type;

// Treat strings and C strings as scalar output objects, not as ranges.
template <class T>
struct is_char_array : std::false_type {};

template <class T, std::size_t N>
struct is_char_array<T[N]>
    : std::bool_constant<std::is_same_v<std::remove_cv_t<T>, char>> {};

template <class T>
struct is_string_like
    : std::bool_constant<
          std::is_same_v<std::decay_t<T>, std::string>
          || std::is_same_v<std::decay_t<T>, const char*>
          || std::is_same_v<std::decay_t<T>, char*>
          || is_char_array<std::remove_reference_t<T>>::value
      > {};

template <class T>
inline constexpr bool is_string_like_v = is_string_like<T>::value;

// ModInt-like type: x.val() is printable, and x can be assigned from long long.
template <class T, class = void>
struct has_val_method : std::false_type {};

template <class T>
struct has_val_method<T, std::void_t<decltype(std::declval<const T&>().val())>>
    : std::true_type {};

template <class T>
inline constexpr bool has_val_method_v = has_val_method<T>::value;

template <class T, class = void>
struct has_static_mod_raw : std::false_type {};

template <class T>
struct has_static_mod_raw<
    T, std::void_t<decltype(T::mod()), decltype(T::raw(std::declval<uint32_t>()))>>
    : std::true_type {};

template <class T>
inline constexpr bool has_static_mod_raw_v = has_static_mod_raw<T>::value;

// libstdc++ before GCC 16 does not classify __int128 as an integral type in
// strict ISO modes such as -std=c++23. Keep the fast-I/O interface independent
// of that implementation detail.
template <class T>
inline constexpr bool is_integral_v =
    std::is_integral_v<T>
    || std::is_same_v<std::remove_cv_t<T>, __int128_t>
    || std::is_same_v<std::remove_cv_t<T>, __uint128_t>;

template <class T>
inline constexpr bool is_signed_v =
    std::is_signed_v<T>
    || std::is_same_v<std::remove_cv_t<T>, __int128_t>;

template <class T>
struct make_unsigned {
    using type = std::make_unsigned_t<T>;
};

template <>
struct make_unsigned<__int128_t> {
    using type = __uint128_t;
};

template <>
struct make_unsigned<__uint128_t> {
    using type = __uint128_t;
};

template <class T>
using make_unsigned_t = typename make_unsigned<std::remove_cv_t<T>>::type;

}  // namespace internal

struct FastInput {
    static constexpr int buffer_size = 1 << 20;

   private:
    std::FILE* _stream;
    char _buffer[buffer_size];
    int _position;
    int _length;
    int _file_descriptor;
    bool _streaming;

    bool refill() {
        _position = 0;
        if (_streaming) {
            ssize_t length;
            do {
                length = ::read(_file_descriptor, _buffer, buffer_size);
            } while (length < 0 && errno == EINTR);
            if (length <= 0) {
                _length = 0;
                return false;
            }
            _length = int(length);
        } else {
            _length = int(std::fread(_buffer, 1, buffer_size, _stream));
        }
        return _length != 0;
    }

    template <class T>
    bool read_integer_from_stream(T& value) {
        if (!skip_spaces()) return false;
        int c = read_char_raw();

        bool negative = false;
        if (c == '-') {
            negative = true;
            c = read_char_raw();
        }

        if constexpr (internal::is_signed_v<T>) {
            T result = 0;
            while ('0' <= c && c <= '9') {
                result = negative ? result * 10 - (c - '0')
                                  : result * 10 + (c - '0');
                c = read_char_raw();
            }
            value = result;
        } else {
            T result = 0;
            while ('0' <= c && c <= '9') {
                result = result * 10 + T(c - '0');
                c = read_char_raw();
            }
            value = negative ? T(0) - result : result;
        }
        return true;
    }

    bool prepare_number() {
        if (_length - _position >= 64) return true;
        const int remaining = _length - _position;
        if (remaining > 0) std::memmove(_buffer, _buffer + _position, remaining);
        const int added = int(std::fread(_buffer + remaining, 1, buffer_size - remaining, _stream));
        _position = 0;
        _length = remaining + added;
        if (_length < buffer_size) _buffer[_length] = '\0';
        return _length != 0;
    }

   public:
    explicit FastInput(std::FILE* stream = stdin)
        : _stream(stream),
          _position(0),
          _length(0),
          _file_descriptor(::fileno(stream)),
          _streaming([&] {
              struct stat status;
              return _file_descriptor >= 0
                     && ::fstat(_file_descriptor, &status) == 0
                     && !S_ISREG(status.st_mode);
          }()) {}

    FastInput(const FastInput&) = delete;
    FastInput& operator=(const FastInput&) = delete;

    int read_char_raw() {
        if (_position == _length && !refill()) return EOF;
        return _buffer[_position++];
    }

    bool skip_spaces() {
        int c = read_char_raw();
        while (c != EOF && c <= ' ') c = read_char_raw();
        if (c == EOF) return false;
        --_position;
        return true;
    }

    bool read(char& value) {
        if (!skip_spaces()) return false;
        value = char(read_char_raw());
        return true;
    }

    bool read(std::string& value) {
        if (!skip_spaces()) return false;
        value.clear();
        while (true) {
            const int begin = _position;
            while (_position < _length &&
                   static_cast<unsigned char>(_buffer[_position]) > ' ') {
                ++_position;
            }
            value.append(_buffer + begin, _position - begin);
            if (_position < _length) {
                ++_position;
                return true;
            }
            if (!refill()) return true;
        }
    }

    bool read(bool& value) {
        int x;
        if (!read(x)) return false;
        value = x != 0;
        return true;
    }

    template <class T>
    std::enable_if_t<
        internal::is_integral_v<T>
            && !std::is_same_v<std::remove_cv_t<T>, bool>
            && !std::is_same_v<std::remove_cv_t<T>, char>,
        bool
    >
    read(T& value) {
        if (_streaming) return read_integer_from_stream(value);
        if (!prepare_number()) return false;
        int c = static_cast<unsigned char>(_buffer[_position++]);
        while (c <= ' ') c = static_cast<unsigned char>(_buffer[_position++]);

        bool negative = false;
        if (c == '-') {
            negative = true;
            c = static_cast<unsigned char>(_buffer[_position++]);
        }

        if constexpr (internal::is_signed_v<T>) {
            T result = 0;
            while ('0' <= c && c <= '9') {
                const int first = c - '0';
                const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
                if (0 <= second && second <= 9) {
                    result = negative ? result * 100 - (first * 10 + second)
                                      : result * 100 + (first * 10 + second);
                    ++_position;
                } else {
                    result = negative ? result * 10 - first : result * 10 + first;
                }
                c = static_cast<unsigned char>(_buffer[_position++]);
            }
            value = result;
        } else {
            T result = 0;
            while ('0' <= c && c <= '9') {
                const unsigned first = unsigned(c - '0');
                const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
                if (0 <= second && second <= 9) {
                    result = result * 100 + T(first * 10 + unsigned(second));
                    ++_position;
                } else {
                    result = result * 10 + T(first);
                }
                c = static_cast<unsigned char>(_buffer[_position++]);
            }
            value = negative ? T(0) - result : result;
        }
        if (_position > _length) _position = _length;
        return true;
    }

    template <class T>
    std::enable_if_t<std::is_floating_point_v<T>, bool>
    read(T& value) {
        if (!skip_spaces()) return false;
        int c = read_char_raw();
        bool negative = false;
        if (c == '-' || c == '+') {
            negative = c == '-';
            c = read_char_raw();
        }

        long double result = 0;
        while ('0' <= c && c <= '9') {
            result = result * 10 + (c - '0');
            c = read_char_raw();
        }
        if (c == '.') {
            long double place = 0.1L;
            c = read_char_raw();
            while ('0' <= c && c <= '9') {
                result += (c - '0') * place;
                place *= 0.1L;
                c = read_char_raw();
            }
        }
        if (c == 'e' || c == 'E') {
            c = read_char_raw();
            bool exponent_negative = false;
            if (c == '-' || c == '+') {
                exponent_negative = c == '-';
                c = read_char_raw();
            }
            int exponent = 0;
            while ('0' <= c && c <= '9') {
                exponent = exponent * 10 + (c - '0');
                c = read_char_raw();
            }
            long double scale = 1;
            long double power = 10;
            while (exponent > 0) {
                if (exponent & 1) scale *= power;
                power *= power;
                exponent >>= 1;
            }
            result = exponent_negative ? result / scale : result * scale;
        }
        value = static_cast<T>(negative ? -result : result);
        return true;
    }

    template <class T>
    std::enable_if_t<
        internal::has_val_method_v<T>
            && !internal::is_integral_v<T>
            && !internal::is_range_v<T>,
        bool
    >
    read(T& value) {
        long long x;
        if (!read(x)) return false;
        if constexpr (internal::has_static_mod_raw_v<T>) {
            if (x >= 0 && uint64_t(x) < uint64_t(T::mod())) {
                value = T::raw(uint32_t(x));
            } else {
                value = T(x);
            }
        } else {
            value = T(x);
        }
        return true;
    }

    template <class First, class Second>
    bool read(std::pair<First, Second>& value) {
        if (!read(value.first)) return false;
        return read(value.second);
    }

    template <class Range>
    std::enable_if_t<
        internal::is_range_v<Range>
            && !internal::is_string_like_v<Range>,
        bool
    >
    read(Range& range) {
        using StoredValue = internal::range_stored_value_t<Range>;
        constexpr bool nested = internal::is_range_v<StoredValue>
                                && !internal::is_string_like_v<StoredValue>;

        for (auto&& value : range) {
            if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
                bool x;
                if (!read(x)) return false;
                value = x;
            } else {
                if (!read(value)) return false;
            }
        }
        return true;
    }

    template <class First, class Second, class... Rest>
    bool read(First& first, Second& second, Rest&... rest) {
        if (!read(first)) return false;
        return read(second, rest...);
    }

    template <class T>
    FastInput& operator>>(T& value) {
        if (!read(value)) std::abort();
        return *this;
    }
};

struct FastOutput {
    static constexpr int buffer_size = 1 << 20;

   private:
    inline static const auto digit_quads = [] {
        std::array<char, 40000> result{};
        for (int i = 0; i < 10000; i++) {
            int value = i;
            for (int j = 3; j >= 0; j--) {
                result[4 * i + j] = char('0' + value % 10);
                value /= 10;
            }
        }
        return result;
    }();

    std::FILE* _stream;
    char _buffer[buffer_size];
    int _position;
    int _precision;
    std::chars_format _float_format;
    char _range_separator;
    std::string* _capture = nullptr;

    template <class T>
    std::string format_cell(const T& value) {
        std::string result;
        struct CaptureGuard {
            std::string*& target;
            std::string* previous;
            ~CaptureGuard() { target = previous; }
        } guard{_capture, _capture};
        _capture = &result;
        write(value);
        return result;
    }

    template <class Matrix>
    void write_aligned_matrix(const Matrix& matrix) {
        std::vector<std::vector<std::string>> rows;
        std::vector<std::size_t> widths;
        for (const auto& row : matrix) {
            auto& cells = rows.emplace_back();
            std::size_t column = 0;
            for (const auto& value : row) {
                cells.push_back(format_cell(value));
                if (column == widths.size()) widths.push_back(0);
                widths[column] = std::max(widths[column], cells.back().size());
                ++column;
            }
        }
        bool first = true;
        for (const auto& row : rows) {
            if (!first) write_char('\n');
            first = false;
            for (std::size_t column = 0; column < row.size(); ++column) {
                if (column != 0) write_char(_range_separator);
                for (std::size_t padding = row[column].size();
                     padding < widths[column]; ++padding) {
                    write_char(' ');
                }
                write(row[column]);
            }
        }
    }

   public:
    explicit FastOutput(std::FILE* stream = stdout)
        : _stream(stream),
          _position(0),
          _precision(6),
          _float_format(std::chars_format::general),
          _range_separator(' ') {
        if (_stream == stdout
            && internal::standard_output_instance == nullptr) {
            internal::standard_output_instance = this;
        }
    }

    FastOutput(const FastOutput&) = delete;
    FastOutput& operator=(const FastOutput&) = delete;

    ~FastOutput() {
        flush();
        if (internal::standard_output_instance == this) {
            internal::standard_output_instance = nullptr;
        }
    }

    void flush() {
        if (_position != 0) {
            std::fwrite(_buffer, 1, _position, _stream);
            _position = 0;
        }
        std::fflush(_stream);
    }

    void write_char(char c) {
        if (_capture != nullptr) {
            _capture->push_back(c);
            return;
        }
        if (_position == buffer_size) flush();
        _buffer[_position++] = c;
    }

    void write(const char* s) {
        while (*s != '\0') write_char(*s++);
    }

    void write(const std::string& s) {
        if (_capture != nullptr) {
            _capture->append(s);
            return;
        }
        std::size_t position = 0;
        while (position < s.size()) {
            if (_position == buffer_size) flush();
            const std::size_t copied =
                std::min<std::size_t>(buffer_size - _position, s.size() - position);
            std::memcpy(_buffer + _position, s.data() + position, copied);
            _position += int(copied);
            position += copied;
        }
    }

    void write(char c) {
        write_char(c);
    }

    void write(bool value) {
        write_char(value ? '1' : '0');
    }

    template <class T>
    std::enable_if_t<std::is_floating_point_v<T>>
    write(T value) {
        char digits[128];
        auto [end, error] = std::to_chars(
            digits,
            digits + sizeof(digits),
            value,
            _float_format,
            _precision
        );
        if (error != std::errc()) std::abort();
        for (const char* pointer = digits; pointer != end; pointer++) {
            write_char(*pointer);
        }
    }

    template <class T>
    std::enable_if_t<
        internal::is_integral_v<T>
            && !std::is_same_v<std::remove_cv_t<T>, bool>
            && !std::is_same_v<std::remove_cv_t<T>, char>
    >
    write(T value) {
        using Raw = std::remove_cv_t<T>;
        using Unsigned = internal::make_unsigned_t<Raw>;

        Unsigned magnitude;
        if constexpr (internal::is_signed_v<Raw>) {
            if (value < 0) {
                write_char('-');
                magnitude = Unsigned(0) - Unsigned(value);
            } else {
                magnitude = Unsigned(value);
            }
        } else {
            magnitude = value;
        }

        if (magnitude == 0) {
            write_char('0');
            return;
        }

        unsigned chunks[16];
        int count = 0;
        while (magnitude >= 10000) {
            const Unsigned quotient = magnitude / 10000;
            chunks[count++] = unsigned(magnitude - quotient * 10000);
            magnitude = quotient;
        }
        if (_capture == nullptr && _position > buffer_size - 64) flush();
        char captured[64];
        char* const begin = _capture != nullptr ? captured : _buffer + _position;
        char* destination = begin;
        const unsigned leading = unsigned(magnitude);
        const char* first = digit_quads.data() + 4 * leading;
        int skip = leading < 10 ? 3 : leading < 100 ? 2 : leading < 1000 ? 1 : 0;
        for (; skip < 4; skip++) *destination++ = first[skip];
        while (count--) {
            const char* digits = digit_quads.data() + 4 * chunks[count];
            std::memcpy(destination, digits, 4);
            destination += 4;
        }
        if (_capture != nullptr) {
            _capture->append(begin, destination - begin);
        } else {
            _position += int(destination - begin);
        }
    }

    template <class T>
    std::enable_if_t<
        internal::has_val_method_v<T>
            && !internal::is_integral_v<T>
            && !internal::is_range_v<T>
    >
    write(const T& value) {
        write(value.val());
    }

    template <class First, class Second>
    void write(const std::pair<First, Second>& value) {
        write(value.first);
        write_char(' ');
        write(value.second);
    }

    template <class Range>
    std::enable_if_t<
        internal::is_range_v<Range>
            && !internal::is_string_like_v<Range>
    >
    write(const Range& range) {
        using StoredValue = internal::range_stored_value_t<const Range>;
        constexpr bool nested = internal::is_range_v<StoredValue>
                                && !internal::is_string_like_v<StoredValue>;

        bool first = true;
        for (const auto& value : range) {
            if (!first) write_char(nested ? '\n' : _range_separator);
            first = false;
            if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
                write(static_cast<bool>(value));
            } else {
                write(value);
            }
        }
    }

    template <class First, class... Rest>
    void print(const First& first, const Rest&... rest) {
        write(first);
        ((write_char(' '), write(rest)), ...);
    }

    void println() {
        write_char('\n');
    }

    void set_precision(int precision) {
        _precision = precision;
    }

    void set_fixed(int precision = 6) {
        _float_format = std::chars_format::fixed;
        _precision = precision;
    }

    void set_general(int precision = 6) {
        _float_format = std::chars_format::general;
        _precision = precision;
    }

    void set_range_separator(char separator) {
        _range_separator = separator;
    }

    template <class Matrix>
    void write_aligned(const Matrix& matrix) {
        using Row = internal::range_stored_value_t<const Matrix>;
        using Cell = internal::range_stored_value_t<const Row>;
        static_assert(internal::is_range_v<Row> && !internal::is_string_like_v<Row>,
                      "write_aligned requires a two-dimensional range");
        static_assert(!internal::is_range_v<Cell> || internal::is_string_like_v<Cell>,
                      "write_aligned requires scalar cells");
        write_aligned_matrix(matrix);
    }

    template <class Matrix>
    void println_aligned(const Matrix& matrix) {
        write_aligned(matrix);
        write_char('\n');
    }

    template <class... Args>
    void println(const Args&... args) {
        print(args...);
        write_char('\n');
    }

    template <class T>
    FastOutput& operator<<(const T& value) {
        write(value);
        return *this;
    }
};

}  // namespace utilities
}  // namespace m1une


#line 6 "verify/algo/search/golden_section_search.test.cpp"
#include <random>
#line 8 "verify/algo/search/golden_section_search.test.cpp"

#line 1 "algo/search/golden_section_search.hpp"



#line 5 "algo/search/golden_section_search.hpp"
#include <concepts>
#include <numeric>
#line 10 "algo/search/golden_section_search.hpp"

namespace m1une {
namespace algo {

namespace detail {

template <std::integral Int, class F, class Compare>
Int integer_golden_section_search(Int left, Int right, F f, Compare comp) {
    assert(left < right);

    using UInt = std::make_unsigned_t<Int>;
    using Uint128 = unsigned __int128;
    const Uint128 n = static_cast<Uint128>(static_cast<UInt>(right) - static_cast<UInt>(left));

    auto add_offset = [left](Uint128 offset) -> Int {
        if constexpr (std::signed_integral<Int>) {
            if (left < 0) {
                const Uint128 negative_count = static_cast<Uint128>(-(left + 1)) + 1;
                if (offset < negative_count) {
                    return static_cast<Int>(left + static_cast<Int>(offset));
                }
                return static_cast<Int>(offset - negative_count);
            }
        }
        return static_cast<Int>(left + static_cast<Int>(offset));
    };

    using Value = std::decay_t<decltype(f(left))>;
    struct Evaluated {
        Uint128 pos;
        const Value* value;
    };

    Uint128 fib0 = 1;
    Uint128 fib1 = 1;
    Uint128 fib2 = 2;
    int k = 2;
    while (fib2 < n) {
        fib0 = fib1;
        fib1 = fib2;
        fib2 = fib0 + fib1;
        ++k;
    }

    std::vector<std::pair<Uint128, Value>> cache;
    cache.reserve(static_cast<unsigned>(k) + 4);

    auto find_cached = [&](Uint128 pos) -> const Value* {
        for (const auto& [cached_pos, value] : cache) {
            if (cached_pos == pos) return &value;
        }
        return nullptr;
    };

    auto advance_fibonacci = [&]() {
        const Uint128 old0 = fib0;
        const Uint128 old1 = fib1;
        fib0 = old1 - old0;
        fib1 = old0;
        fib2 = old1;
        --k;
    };

    auto eval = [&](Uint128 pos) -> Evaluated {
        if (pos >= n) return Evaluated{pos, nullptr};
        if (const Value* value = find_cached(pos)) return Evaluated{pos, value};
        cache.emplace_back(pos, f(add_offset(pos)));
        return Evaluated{pos, &cache.back().second};
    };

    auto get_value = [&](Uint128 pos) -> const Value& {
        if (const Value* value = find_cached(pos)) return *value;
        cache.emplace_back(pos, f(add_offset(pos)));
        return cache.back().second;
    };

    auto scan = [&](Uint128 scan_left, Uint128 scan_right) -> Int {
        Int best = add_offset(scan_left);
        const Value* best_value = &get_value(scan_left);
        for (Uint128 pos = scan_left + 1; pos <= scan_right; ++pos) {
            Int x = add_offset(pos);
            const Value& value = get_value(pos);
            if (comp(value, *best_value)) {
                best = x;
                best_value = &value;
            }
        }
        return best;
    };

    if (n <= 3) return scan(0, n - 1);

    auto better = [&](const Evaluated& a, const Evaluated& b) -> bool {
        if ((a.value != nullptr) != (b.value != nullptr)) return a.value != nullptr;
        if (a.value == nullptr) return false;
        return comp(*a.value, *b.value);
    };

    Uint128 left_pos = 0;
    Uint128 right_pos = fib2 - 1;
    Uint128 x1 = left_pos + fib0 - 1;
    Uint128 x2 = left_pos + fib1 - 1;
    Evaluated y1 = eval(x1);
    Evaluated y2 = eval(x2);

    while (k > 2) {
        if (better(y2, y1)) {
            left_pos = x1 + 1;
            x1 = x2;
            y1 = y2;
            advance_fibonacci();
            if (k == 2) break;
            x2 = left_pos + fib1 - 1;
            y2 = eval(x2);
        } else {
            right_pos = x2;
            x2 = x1;
            y2 = y1;
            advance_fibonacci();
            if (k == 2) break;
            x1 = left_pos + fib0 - 1;
            y1 = eval(x1);
        }
    }

    const Uint128 last_valid = n - 1;
    if (right_pos > last_valid) right_pos = last_valid;
    assert(left_pos <= right_pos);
    return scan(left_pos, right_pos);
}

}  // namespace detail

template <std::integral Int, class F>
Int golden_section_search_argmin(Int left, Int right, F f) {
    return detail::integer_golden_section_search(left, right, f, [](const auto& a, const auto& b) { return a < b; });
}

template <std::integral Int, class F>
Int golden_section_search_argmax(Int left, Int right, F f) {
    return detail::integer_golden_section_search(left, right, f, [](const auto& a, const auto& b) { return b < a; });
}

template <class F>
double golden_section_search_argmin(double left, double right, F f, int iterations = 100) {
    assert(left <= right);
    assert(0 <= iterations);
    if (left == right || iterations == 0) return std::midpoint(left, right);

    constexpr double inv_phi = 0.6180339887498948482045868343656381177203;
    double x1 = right - (right - left) * inv_phi;
    double x2 = left + (right - left) * inv_phi;
    auto y1 = f(x1);
    auto y2 = f(x2);

    for (int i = 1; i < iterations; ++i) {
        if (y2 < y1) {
            left = x1;
            x1 = x2;
            y1 = std::move(y2);
            x2 = left + (right - left) * inv_phi;
            y2 = f(x2);
        } else {
            right = x2;
            x2 = x1;
            y2 = std::move(y1);
            x1 = right - (right - left) * inv_phi;
            y1 = f(x1);
        }
    }

    if (y2 < y1) {
        left = x1;
    } else {
        right = x2;
    }
    return std::midpoint(left, right);
}

template <class F>
double golden_section_search_argmax(double left, double right, F f, int iterations = 100) {
    assert(left <= right);
    assert(0 <= iterations);
    if (left == right || iterations == 0) return std::midpoint(left, right);

    constexpr double inv_phi = 0.6180339887498948482045868343656381177203;
    double x1 = right - (right - left) * inv_phi;
    double x2 = left + (right - left) * inv_phi;
    auto y1 = f(x1);
    auto y2 = f(x2);

    for (int i = 1; i < iterations; ++i) {
        if (y1 < y2) {
            left = x1;
            x1 = x2;
            y1 = std::move(y2);
            x2 = left + (right - left) * inv_phi;
            y2 = f(x2);
        } else {
            right = x2;
            x2 = x1;
            y2 = std::move(y1);
            x1 = right - (right - left) * inv_phi;
            y1 = f(x1);
        }
    }

    if (y1 < y2) {
        left = x1;
    } else {
        right = x2;
    }
    return std::midpoint(left, right);
}

}  // namespace algo
}  // namespace m1une


#line 10 "verify/algo/search/golden_section_search.test.cpp"

template <class F>
int naive_argmin(int left, int right, F f) {
    int best = left;
    auto best_value = f(best);
    for (int x = left + 1; x < right; ++x) {
        auto value = f(x);
        if (value < best_value) {
            best = x;
            best_value = value;
        }
    }
    return best;
}

template <class F>
int naive_argmax(int left, int right, F f) {
    int best = left;
    auto best_value = f(best);
    for (int x = left + 1; x < right; ++x) {
        auto value = f(x);
        if (best_value < value) {
            best = x;
            best_value = value;
        }
    }
    return best;
}

void test_integer_argmin() {
    auto convex = [](long long x) {
        return (x - 7) * (x - 7) + 3;
    };
    assert(m1une::algo::golden_section_search_argmin<long long>(-100, 101, convex) == 7);

    auto plateau = [](int x) {
        if (x < 3) return 3 - x;
        if (5 < x) return x - 5;
        return 0;
    };
    assert(m1une::algo::golden_section_search_argmin<int>(-10, 10, plateau) == 3);

    auto increasing = [](int x) {
        return x;
    };
    assert(m1une::algo::golden_section_search_argmin<int>(-7, 9, increasing) == -7);
}

void test_integer_argmax() {
    auto concave = [](int x) {
        return -(x + 2) * (x + 2) + 10;
    };
    assert(m1une::algo::golden_section_search_argmax<int>(-20, 20, concave) == -2);

    auto plateau = [](int x) {
        if (x < -4) return x + 4;
        if (1 < x) return 1 - x;
        return 0;
    };
    assert(m1une::algo::golden_section_search_argmax<int>(-20, 20, plateau) == -4);

    auto increasing = [](int x) {
        return x;
    };
    assert(m1une::algo::golden_section_search_argmax<int>(-7, 9, increasing) == 8);
}

void test_random_integer_arrays() {
    std::mt19937_64 rng(20260709);
    for (int tc = 0; tc < 1000; ++tc) {
        int n = static_cast<int>(rng() % 200) + 1;
        int low = static_cast<int>(rng() % n);
        int high = low + static_cast<int>(rng() % (n - low));

        std::vector<long long> min_values(n);
        long long value = 0;
        for (int i = low - 1; i >= 0; --i) {
            value += static_cast<long long>(rng() % 7) + 1;
            min_values[i] = value;
        }
        value = 0;
        for (int i = high + 1; i < n; ++i) {
            value += static_cast<long long>(rng() % 7) + 1;
            min_values[i] = value;
        }

        int base = static_cast<int>(rng() % 1000) - 500;
        auto min_f = [&](int x) {
            return min_values[x - base];
        };
        int xmin = m1une::algo::golden_section_search_argmin<int>(base, base + n, min_f);
        assert(xmin == naive_argmin(base, base + n, min_f));

        std::vector<long long> max_values(n);
        for (int i = 0; i < n; ++i) max_values[i] = -min_values[i];
        auto max_f = [&](int x) {
            return max_values[x - base];
        };
        int xmax = m1une::algo::golden_section_search_argmax<int>(base, base + n, max_f);
        assert(xmax == naive_argmax(base, base + n, max_f));
    }
}

void test_integer_evaluation_reuse() {
    for (int n = 1; n <= 300; ++n) {
        int base = -n / 2;
        int center = base + n / 3;
        auto value_at = [center](int x) {
            return x < center ? center - x : x - center;
        };

        std::vector<int> count(n);
        auto f = [&](int x) {
            int index = x - base;
            assert(count[index] == 0);
            ++count[index];
            return value_at(x);
        };

        int xmin = m1une::algo::golden_section_search_argmin<int>(base, base + n, f);
        assert(xmin == naive_argmin(base, base + n, value_at));

        std::fill(count.begin(), count.end(), 0);
        auto g = [&](int x) {
            int index = x - base;
            assert(count[index] == 0);
            ++count[index];
            return -value_at(x);
        };
        auto max_value_at = [&](int x) {
            return -value_at(x);
        };

        int xmax = m1une::algo::golden_section_search_argmax<int>(base, base + n, g);
        assert(xmax == naive_argmax(base, base + n, max_value_at));
    }
}

void test_real_argmin() {
    auto convex = [](double x) {
        return (x - 2.75) * (x - 2.75);
    };
    double x = m1une::algo::golden_section_search_argmin(-100.0, 100.0, convex);
    assert(std::abs(x - 2.75) < 1e-9);

    auto increasing = [](double x) {
        return x;
    };
    double left = m1une::algo::golden_section_search_argmin(-3.0, 8.0, increasing);
    assert(std::abs(left + 3.0) < 1e-9);
}

void test_real_argmax() {
    auto concave = [](double x) {
        return -(x + 0.5) * (x + 0.5);
    };
    double x = m1une::algo::golden_section_search_argmax(-100.0, 100.0, concave);
    assert(std::abs(x + 0.5) < 1e-9);

    auto increasing = [](double x) {
        return x;
    };
    double right = m1une::algo::golden_section_search_argmax(-3.0, 8.0, increasing);
    assert(std::abs(right - 8.0) < 1e-9);
}

void test_evaluation_count() {
    int zero_iteration_calls = 0;
    auto f0 = [&](double x) {
        ++zero_iteration_calls;
        return x * x;
    };
    double midpoint = m1une::algo::golden_section_search_argmin(-2.0, 4.0, f0, 0);
    assert(midpoint == 1.0);
    assert(zero_iteration_calls == 0);

    int calls = 0;
    auto f = [&](double x) {
        ++calls;
        return (x - 1.0) * (x - 1.0);
    };
    m1une::algo::golden_section_search_argmin(-5.0, 5.0, f, 37);
    assert(calls == 38);
}

void test_random_quadratics() {
    std::mt19937_64 rng(20260708);
    std::uniform_real_distribution<double> center_dist(-1000.0, 1000.0);
    std::uniform_real_distribution<double> width_dist(0.1, 1000.0);
    std::uniform_real_distribution<double> coef_dist(0.1, 10.0);

    for (int tc = 0; tc < 1000; ++tc) {
        double center = center_dist(rng);
        double left_width = width_dist(rng);
        double right_width = width_dist(rng);
        double coef = coef_dist(rng);
        double left = center - left_width;
        double right = center + right_width;

        auto convex = [=](double x) {
            double dx = x - center;
            return coef * dx * dx;
        };
        double expected_min = center;
        double xmin = m1une::algo::golden_section_search_argmin(left, right, convex, 120);
        assert(std::abs(xmin - expected_min) < 1e-8);

        auto concave = [=](double x) {
            double dx = x - center;
            return -coef * dx * dx;
        };
        double expected_max = center;
        double xmax = m1une::algo::golden_section_search_argmax(left, right, concave, 120);
        assert(std::abs(xmax - expected_max) < 1e-8);
    }
}

int main() {
    m1une::utilities::FastInput fast_input;
    m1une::utilities::FastOutput fast_output;

    test_integer_argmin();
    test_integer_argmax();
    test_random_integer_arrays();
    test_integer_evaluation_reuse();
    test_real_argmin();
    test_real_argmax();
    test_evaluation_count();
    test_random_quadratics();

    long long a, b;
    fast_input >> a >> b;
    fast_output << a + b << '\n';
}
Back to top page