shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/unittest/utility/bit.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// bit.hpp の関数と列挙を愚直な実装とランダムに比較する
// C++17 (__builtin_* で実装) と C++20 (<bit> を呼ぶ) のどちらでも同じ結果になる
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#include "../../../src/utility/bit.hpp"

#include <algorithm>
#include <iostream>
#include <limits>
#include <random>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#if __cplusplus >= 202002L
#include <ranges>
#endif

bool ok = true;

void check(bool cond, const char* what) {
    if (!cond) {
        if (ok) std::cerr << "failed: " << what << std::endl;
        ok = false;
    }
}

int main() {
    std::mt19937_64 rng(314);

    for (int rep = 0; rep < 100000 && ok; rep++) {
        // 0 以上の long long (ビット数もばらつかせる)
        int width = rng() % 63 + 1;
        long long a = static_cast<long long>(rng() >> (64 - width));

        int pc = 0, clz = 0, ctz = 0;
        for (int i = 0; i < 63; i++) pc += a >> i & 1;
        for (int i = 63; i >= 0 && !(a >> i & 1); i--) clz++;
        for (int i = 0; i < 64 && !(a >> i & 1); i++) ctz++;
        check(popcount(a) == pc, "popcount");
        if (a > 0) {
            check(countl_zero(a) == clz, "countl_zero");
            check(countr_zero(a) == ctz, "countr_zero");
        }

        // btoll: 2 進数の文字列 (上位桁から)
        std::string s;
        for (int i = width - 1; i >= 0; i--) s += (a >> i & 1) ? '1' : '0';
        check(btoll(s) == a, "btoll");
        // 1 を表す文字を指定する
        std::string t = s;
        for (char& c : t) c = (c == '1') ? '#' : '.';
        check(btoll(t, '#') == a, "btoll(s, one)");

        // hamming_distance: ビットごとに比べる
        long long b = static_cast<long long>(rng() >> (64 - width));
        int hd = 0;
        for (int i = 0; i < 63; i++) hd += (a >> i & 1) != (b >> i & 1);
        check(hamming_distance(a, b) == hd, "hamming_distance");
    }

    // countl_one / countr_one / bit_width / bit_ceil / bit_floor を愚直な実装と比べる
    for (int rep = 0; rep < 100000 && ok; rep++) {
        int width = rng() % 64;
        long long a = width == 0 ? 0 : static_cast<long long>(rng() >> (64 - width));
        if (rep % 4 == 0) a = (1LL << (rng() % 63)) - rng() % 2;  // 2 の累乗とその前後
        if (a < 0) a = 0;
        int clo = 0, cto = 0, bw = 0;
        for (int i = 63; i >= 0 && (a >> i & 1); i--) clo++;
        for (int i = 0; i < 64 && (a >> i & 1); i++) cto++;
        for (int i = 0; i < 63; i++) {
            if (a >> i & 1) bw = i + 1;
        }
        long long ceil = 1, floor = 0;
        while (ceil < a && ceil <= (1LL << 61)) ceil *= 2;  // a > 2^62 なら使わない
        for (int i = 0; i < 63; i++) {
            if ((1LL << i) <= a) floor = 1LL << i;
        }
        check(countl_one(a) == clo, "countl_one");
        check(countr_one(a) == cto, "countr_one");
        check(bit_width(a) == bw, "bit_width");
        if (a <= (1LL << 62)) check(bit_ceil(a) == ceil, "bit_ceil");
        check(bit_floor(a) == floor, "bit_floor");
    }

    // 1 ビットの操作・位置・変換を愚直な実装と比べる
    for (int rep = 0; rep < 100000 && ok; rep++) {
        int width = rng() % 64;
        long long a = width == 0 ? 0 : static_cast<long long>(rng() >> (64 - width));
        if (rep % 4 == 0) a = 1LL << (rng() % 63);
        int top = -1, low = -1, pc = 0;
        for (int i = 0; i < 63; i++) {
            if (a >> i & 1) {
                top = i;
                if (low < 0) low = i;
                pc++;
            }
        }
        check(has_single_bit(a) == (pc == 1), "has_single_bit");
        check(msb(a) == top && lsb(a) == low, "msb / lsb");
        check(lowbit(a) == (low < 0 ? 0 : 1LL << low), "lowbit");
        check(parity(a) == pc % 2, "parity");
        long long i = rng() % 63;
        bool on = a >> i & 1;
        check(test_bit(a, i) == on, "test_bit");
        check(set_bit(a, i) == (on ? a : a + (1LL << i)), "set_bit");
        check(reset_bit(a, i) == (on ? a - (1LL << i) : a), "reset_bit");
        check(flip_bit(a, i) == (on ? a - (1LL << i) : a + (1LL << i)), "flip_bit");

        // lltob: 桁数を省略すると先頭に 0 を付けない
        std::string s;
        for (int j = std::max(top, 0); j >= 0; j--) s += (a >> j & 1) ? '1' : '0';
        check(lltob(a) == s && btoll(lltob(a)) == a, "lltob");
        long long n = std::max(top + 1, 0) + rng() % 3;
        if (n > 63) n = 63;
        if (n == 0) n = 1;
        check(lltob(a, n) == std::string(n - s.size(), '0') + s, "lltob(a, n)");
        std::string t = lltob(a, n, '#', '.');
        check(static_cast<long long>(t.size()) == n && btoll(t, '#') == a, "lltob(a, n, one, zero)");

        // reverse_bits / rotate_left / rotate_right: n ビットの各位置を動かす
        long long rev = 0, rl = 0, rr = 0, k = static_cast<long long>(rng() % 200) - 100;
        long long km = ((k % n) + n) % n;
        for (int j = 0; j < n; j++) {
            if (a >> j & 1) {
                rev |= 1LL << (n - 1 - j);
                rl |= 1LL << ((j + km) % n);
                rr |= 1LL << ((j - km + n) % n);
            }
        }
        check(reverse_bits(a, n) == rev, "reverse_bits");
        check(rotate_left(a, k, n) == rl, "rotate_left");
        check(rotate_right(a, k, n) == rr, "rotate_right");

        // gray_code: 逆変換で戻り、隣り合う値で 1 ビットだけ変わる
        check(inverse_gray_code(gray_code(a)) == a, "inverse_gray_code");
        if (a < std::numeric_limits<long long>::max()) check(popcount(gray_code(a) ^ gray_code(a + 1)) == 1, "gray_code");

        // kth_set_bit
        if (pc > 0) {
            long long kk = rng() % pc, pos = -1;
            for (int j = 0, c = 0; j < 63; j++) {
                if (a >> j & 1) {
                    if (c == kk) pos = j;
                    c++;
                }
            }
            check(kth_set_bit(a, kk) == pos, "kth_set_bit");
        }
    }
    // xor_upto / bit_count_upto: 小さい n は 1 つずつ数える
    {
        long long x = 0;
        std::vector<long long> cnt(63, 0);
        for (long long n = 0; n < 5000 && ok; n++) {
            x ^= n;
            check(xor_upto(n) == x, "xor_upto");
            for (int i = 0; i < 63; i++) {
                cnt[i] += n >> i & 1;
                check(bit_count_upto(n, i) == cnt[i], "bit_count_upto");
            }
        }
        long long mx = std::numeric_limits<long long>::max();
        // 大きい n: bit_count_upto の和は 0..n の popcount の和で、0..n を 2 つに分けて数えても同じ
        for (int rep = 0; rep < 1000 && ok; rep++) {
            long long n = static_cast<long long>(rng() >> 1);
            if (n == mx) n--;
            long long m = static_cast<long long>(rng() % 1000);
            if (n < m) continue;
            for (int i = 0; i < 63; i++) {
                long long direct = 0;
                for (long long v = n - m + 1; v <= n; v++) direct += v >> i & 1;
                check(bit_count_upto(n, i) - (n - m < 0 ? 0 : bit_count_upto(n - m, i)) == direct, "bit_count_upto 大きい n");
            }
            long long xr = xor_upto(n - m);
            for (long long v = n - m + 1; v <= n; v++) xr ^= v;
            check(xor_upto(n) == xr, "xor_upto 大きい n");
        }
        check(bit_count_upto(mx - 1, 62) == mx - (1LL << 62), "bit_count_upto 上限");
        check(xor_upto(0) == 0 && xor_upto(3) == 0 && xor_upto(mx - 1) == mx && xor_upto(mx) == 0, "xor_upto 境界");
    }

    // subsets / supersets / bits / combinations_mask / add_one / remove_one を、すべての値を調べる愚直な方法と比べる
    for (int rep = 0; rep < 300 && ok; rep++) {
        int n = rng() % 9;
        long long mask = static_cast<long long>(rng() % (1ULL << n));
        std::vector<long long> sub, sup, pos, got;
        for (long long s = (1LL << n) - 1; s >= 0; s--) {
            if ((s & mask) == s) sub.push_back(s);  // 降順
        }
        for (long long s = 0; s < (1LL << n); s++) {
            if ((s & mask) == mask) sup.push_back(s);  // 昇順
        }
        for (int i = 0; i < n; i++) {
            if (mask >> i & 1) pos.push_back(i);
        }
        got.clear();
        for (long long s : subsets(mask)) got.push_back(s);
        check(got == sub, "subsets");
        got.clear();
        for (long long s : supersets(mask, n)) got.push_back(s);
        check(got == sup, "supersets");
        got.clear();
        for (long long i : bits(mask)) got.push_back(i);
        check(got == pos, "bits");
        // add_one / remove_one: 1 つ足した (除いた) 集合と、その位置の組
        std::vector<std::pair<long long, long long>> add, rem, gp;
        for (int i = 0; i < n; i++) {
            if (mask >> i & 1)
                rem.emplace_back(i, mask ^ (1LL << i));
            else
                add.emplace_back(i, mask | (1LL << i));
        }
        for (auto [i, t] : add_one(mask, n)) gp.emplace_back(i, t);
        check(gp == add, "add_one");
        gp.clear();
        for (auto [i, t] : remove_one(mask)) gp.emplace_back(i, t);
        check(gp == rem, "remove_one");
        // subsets_of_size: mask の部分集合で要素数 k のもの (昇順)
        for (int k = 0; k <= n + 1; k++) {
            std::vector<long long> want;
            for (long long s = 0; s < (1LL << n); s++) {
                if ((s & mask) == s && __builtin_popcountll(s) == k) want.push_back(s);
            }
            got.clear();
            for (long long s : subsets_of_size(mask, k)) got.push_back(s);
            check(got == want, "subsets_of_size");
        }
        // next_combination_mask: 立っているビットの数が同じで次に大きい値
        if (mask > 0) {
            long long want = -1;
            for (long long s = mask + 1; s < (1LL << 12); s++) {
                if (__builtin_popcountll(s) == __builtin_popcountll(mask)) {
                    want = s;
                    break;
                }
            }
            check(next_combination_mask(mask) == want, "next_combination_mask");
        }
        for (int k = 0; k <= n + 1; k++) {
            std::vector<long long> comb;
            for (long long s = 0; s < (1LL << n); s++) {
                if (__builtin_popcountll(s) == k) comb.push_back(s);
            }
            got.clear();
            for (long long s : combinations_mask(n, k)) got.push_back(s);
            check(got == comb, "combinations_mask");
        }
    }
    {
        // 大きいビット幅と境界
        long long cnt = 0, last = -1;
        for (long long s : combinations_mask(62, 61)) cnt++, last = s;
        check(cnt == 62 && last == (1LL << 62) - 2, "combinations_mask(62, 61)");
        cnt = 0;
        for (long long s : supersets((1LL << 62) - 2, 62)) cnt += s;
        check(cnt == 2 * ((1LL << 62) - 2) + 1, "supersets 62 ビット");
        std::vector<long long> got;
        for (long long i : bits(std::numeric_limits<long long>::max())) got.push_back(i);
        check(static_cast<long long>(got.size()) == 63 && got.back() == 62, "bits(最大値)");
        got.clear();
        for (long long s : subsets(0)) got.push_back(s);
        check(got == std::vector<long long>{0}, "subsets(0)");
        // constexpr でも使える
        constexpr long long sum = [] {
            long long r = 0;
            for (long long s : subsets(0b1011)) r += s;
            for (long long i : bits(0b1011)) r += i;
            return r;
        }();
        static_assert(sum == 44 + 4);
        constexpr long long sum2 = [] {
            long long r = 0;
            for (auto [i, t] : add_one(0b0101, 4)) r += i * 100 + t;  // (1, 0111), (3, 1101)
            for (auto [i, t] : remove_one(0b0101)) r += i * 100 + t;  // (0, 0100), (2, 0001)
            return r;
        }();
        static_assert(sum2 == (100 + 7) + (300 + 13) + (0 + 4) + (200 + 1));
        got.clear();
        for (auto [i, t] : add_one((1LL << 62) - 2, 62)) got.push_back(i), got.push_back(t);
        check(got == std::vector<long long>{0, (1LL << 62) - 1}, "add_one 62 ビット");
    }

    {
        // subset_pairs: すべての (S, T ⊆ S) を S の昇順、T の降順に
        for (int n = 0; n <= 6 && ok; n++) {
            std::vector<std::pair<long long, long long>> want, gp;
            for (long long s = 0; s < (1LL << n); s++) {
                for (long long t = s; t >= 0; t--) {
                    if ((t & s) == t) want.emplace_back(s, t);
                }
            }
            for (auto [s, t] : subset_pairs(n)) gp.emplace_back(s, t);
            check(gp == want, "subset_pairs");
        }
        // 大きいビット幅と境界
        long long mx = std::numeric_limits<long long>::max();
        check(next_combination_mask(mx) == -1 && next_combination_mask(1LL << 62) == -1, "next_combination_mask 上限");
        check(next_combination_mask((1LL << 62) - 2) == (1LL << 62) + (1LL << 60) - 1, "next_combination_mask 62 ビット");
        std::vector<long long> got;
        for (long long s : subsets_of_size(mx, 62)) got.push_back(s);
        check(static_cast<long long>(got.size()) == 63 && got.front() == (1LL << 62) - 1 && got.back() == mx - 1, "subsets_of_size 63 ビット");
        got.clear();
        for (long long s : subsets_of_size(0b1010, 0)) got.push_back(s);
        check(got == std::vector<long long>{0}, "subsets_of_size(k = 0)");
        check(rotate_left(1, 1, 63) == 2 && rotate_left(1LL << 62, 1, 63) == 1 && rotate_right(1, 1, 63) == (1LL << 62), "rotate 63 ビット");
        check(reverse_bits(1, 63) == (1LL << 62) && inverse_gray_code(gray_code(mx)) == mx, "63 ビット");
        check(kth_set_bit(mx, 62) == 62 && kth_set_bit(1LL << 62, 0) == 62, "kth_set_bit 63 ビット");
        check(lltob(0) == "0" && lltob(5) == "101" && lltob(5, 5) == "00101" && lltob(0, 3, '#', '.') == "...", "lltob 決まった値");
        check(msb(0) == -1 && lsb(0) == -1 && lowbit(0) == 0 && msb(mx) == 62, "msb / lsb / lowbit 境界");
        constexpr long long sum = [] {
            long long r = 0;
            for (long long s : subsets_of_size(0b1101, 2)) r += s;  // 0101, 1001, 1100
            for (auto [s, t] : subset_pairs(2)) r += s * 10 + t;    // 3^2 = 9 組
            return r;
        }();
        static_assert(sum == (5 + 9 + 12) + (0 + 11 + 10 + 22 + 20 + 33 + 32 + 31 + 30));
        static_assert(has_single_bit(64) && !has_single_bit(0) && !has_single_bit(6));
        static_assert(gray_code(5) == 7 && inverse_gray_code(7) == 5 && rotate_left(0b0011, 3, 4) == 0b1001);
    }

    {
        auto verify_range = [&](auto range, const auto& expected) {
            using Value = decltype(*range.begin());
            check(std::vector<Value>(range.begin(), range.end()) == expected, "iterator range constructor");
            auto it = range.begin(), independent = it;
            decltype(it) assigned;
            assigned = it;
            if (it != range.end()) {
                const auto first = *it++;
                check(first == *independent && first == *assigned, "copy / postfix increment");
                ++independent;
                check(it == independent, "independent iterators");
            }
#if __cplusplus >= 202002L
            static_assert(std::ranges::forward_range<decltype(range)>);
            static_assert(std::ranges::viewable_range<decltype(range)>);
            auto selected = std::move(range) | std::views::filter([](const auto&) { return true; });
            std::vector<Value> actual;
            std::ranges::copy(selected, std::back_inserter(actual));
            check(actual == expected, "rvalue range / views::filter");
#endif
        };
        verify_range(subsets(5), std::vector<long long>{5, 4, 1, 0});
        verify_range(supersets(1, 3), std::vector<long long>{1, 3, 5, 7});
        verify_range(bits(5), std::vector<long long>{0, 2});
        verify_range(bits(0), std::vector<long long>{});
        verify_range(combinations_mask(3, 2), std::vector<long long>{3, 5, 6});
        verify_range(combinations_mask(2, 3), std::vector<long long>{});
        verify_range(subsets_of_size(5, 1), std::vector<long long>{1, 4});
        verify_range(add_one(1, 3), std::vector<std::pair<long long, long long>>{{1, 3}, {2, 5}});
        verify_range(remove_one(5), std::vector<std::pair<long long, long long>>{{0, 4}, {2, 1}});
        verify_range(subset_pairs(1), std::vector<std::pair<long long, long long>>{{0, 0}, {1, 1}, {1, 0}});
    }

    // 0 のときは C++20 の <bit> と同じ値
    check(countl_zero(0) == 64 && countr_zero(0) == 64, "countl_zero / countr_zero(0)");
    check(countl_one(0) == 0 && countr_one(0) == 0, "countl_one / countr_one(0)");
    check(bit_width(0) == 0 && bit_ceil(0) == 1 && bit_floor(0) == 0, "bit_width / bit_ceil / bit_floor(0)");
    check(bit_ceil(1LL << 62) == (1LL << 62) && bit_ceil((1LL << 61) + 1) == (1LL << 62), "bit_ceil 上限");
    check(countr_one(std::numeric_limits<long long>::max()) == 63 && bit_width(std::numeric_limits<long long>::max()) == 63, "最大値");

    // 戻り値の型は C++17 でも C++20 でも long long
    static_assert(std::is_same_v<decltype(popcount(1)), long long>);
    static_assert(std::is_same_v<decltype(countl_zero(1)), long long>);
    static_assert(std::is_same_v<decltype(countr_zero(1)), long long>);
    static_assert(std::is_same_v<decltype(countl_one(1)), long long>);
    static_assert(std::is_same_v<decltype(countr_one(1)), long long>);
    static_assert(std::is_same_v<decltype(bit_width(1)), long long>);
    static_assert(std::is_same_v<decltype(bit_ceil(1)), long long>);
    static_assert(std::is_same_v<decltype(bit_floor(1)), long long>);
    static_assert(bit_width(5) == 3 && bit_ceil(5) == 8 && bit_floor(5) == 4 && countl_zero(0) == 64);

    // 決まった値
    check(popcount(0) == 0 && popcount((1LL << 62) - 1) == 62, "popcount 境界");
    check(countl_zero(1) == 63 && countr_zero(1LL << 62) == 62, "countl_zero / countr_zero 境界");
    check(hamming_distance(5, 3) == 2 && hamming_distance(7, 7) == 0, "hamming_distance 決まった値");
    check(btoll("") == 0 && btoll("0") == 0 && btoll("101") == 5, "btoll 決まった値");

    if (ok) std::cout << "Hello World" << std::endl;
}
#line 1 "test/unittest/utility/bit.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// bit.hpp の関数と列挙を愚直な実装とランダムに比較する
// C++17 (__builtin_* で実装) と C++20 (<bit> を呼ぶ) のどちらでも同じ結果になる
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#line 2 "src/utility/bit.hpp"

/**
 * @file bit.hpp
 * @brief ビット演算
 */

#include <cassert>
#include <cstddef>
#include <iterator>
#include <string>
#include <utility>

/**
 * @brief 2進数の文字列をlong longにする
 */
inline long long btoll(std::string s, char one = '1') {
    long long res = 0;
    for (char c : s) {
        res <<= 1;
        if (c == one) ++res;
    }
    return res;
}

#if __cplusplus < 202000L

// C++20 の <bit> と同じ値を返す (0 のときも同じ)

/**
 * @brief 立っているビットを数える
 * __builtin_popcountll
 */
inline constexpr long long popcount(long long a) {
    assert(a >= 0);
    return __builtin_popcountll(static_cast<unsigned long long>(a));
}
/**
 * @brief 左から連続した0のビットを数える
 * __builtin_clzll
 */
inline constexpr long long countl_zero(long long a) {
    assert(a >= 0);
    return a == 0 ? 64 : __builtin_clzll(static_cast<unsigned long long>(a));
}
/**
 * @brief 左から連続した1のビットを数える
 */
inline constexpr long long countl_one(long long a) {
    assert(a >= 0);
    unsigned long long x = ~static_cast<unsigned long long>(a);
    return x == 0 ? 64 : __builtin_clzll(x);
}
/**
 * @brief 右から連続した0のビットを数える
 * __builtin_ctzll
 */
inline constexpr long long countr_zero(long long a) {
    assert(a >= 0);
    return a == 0 ? 64 : __builtin_ctzll(static_cast<unsigned long long>(a));
}
/**
 * @brief 右から連続した1のビットを数える
 */
inline constexpr long long countr_one(long long a) {
    assert(a >= 0);
    unsigned long long x = ~static_cast<unsigned long long>(a);
    return x == 0 ? 64 : __builtin_ctzll(x);
}
/**
 * @brief 値を表現するために必要なビット幅を求める
 */
inline constexpr long long bit_width(long long a) {
    assert(a >= 0);
    return 64 - countl_zero(a);
}
/**
 * @brief 整数値を2の累乗値に切り上げる
 */
inline constexpr long long bit_ceil(long long a) {
    assert(0 <= a && a <= (1LL << 62));
    return a <= 1 ? 1 : 1LL << bit_width(a - 1);
}
/**
 * @brief 整数値を2の累乗値に切り下げる
 */
inline constexpr long long bit_floor(long long a) {
    assert(a >= 0);
    return a == 0 ? 0 : 1LL << (bit_width(a) - 1);
}
/**
 * @brief 2 の累乗か (ちょうど 1 つのビットが立っているか)
 */
inline constexpr bool has_single_bit(long long a) {
    assert(a >= 0);
    return a != 0 && (a & (a - 1)) == 0;
}

#else

#include <bit>
#define BIT_FUNC_EXPAND(func)                                 \
    inline constexpr long long func(long long a) {            \
        assert(a >= 0);                                       \
        return std::func(static_cast<unsigned long long>(a)); \
    }

/**
 * @brief 立っているビットを数える
 */
BIT_FUNC_EXPAND(popcount)
/**
 * @brief 左から連続した0のビットを数える
 */
BIT_FUNC_EXPAND(countl_zero)
/**
 * @brief 左から連続した1のビットを数える
 */
BIT_FUNC_EXPAND(countl_one)
/**
 * @brief 右から連続した0のビットを数える
 */
BIT_FUNC_EXPAND(countr_zero)
/**
 * @brief 右から連続した1のビットを数える
 */
BIT_FUNC_EXPAND(countr_one)
/**
 * @brief 整数値を2の累乗値に切り上げる
 */
inline constexpr long long bit_ceil(long long a) {
    // 結果が long long に収まる範囲に限る
    assert(0 <= a && a <= (1LL << 62));
    return std::bit_ceil(static_cast<unsigned long long>(a));
}
/**
 * @brief 整数値を2の累乗値に切り下げる
 */
BIT_FUNC_EXPAND(bit_floor)
/**
 * @brief 値を表現するために必要なビット幅を求める
 */
BIT_FUNC_EXPAND(bit_width)
/**
 * @brief 2 の累乗か (ちょうど 1 つのビットが立っているか)
 */
inline constexpr bool has_single_bit(long long a) {
    assert(a >= 0);
    return std::has_single_bit(static_cast<unsigned long long>(a));
}

#endif

/**
 * @brief 2 つの整数のハミング距離 (ビットが異なる位置の数)
 */
inline constexpr long long hamming_distance(long long a, long long b) {
    assert(a >= 0 && b >= 0);
    return popcount(a ^ b);
}

/**
 * @brief 最上位の立っているビットの位置 (0 なら -1)
 */
inline constexpr long long msb(long long a) { return bit_width(a) - 1; }
/**
 * @brief 最下位の立っているビットの位置 (0 なら -1)
 */
inline constexpr long long lsb(long long a) {
    assert(a >= 0);
    return a == 0 ? -1 : countr_zero(a);
}
/**
 * @brief 最下位の立っているビットだけを残した値 a & -a (0 なら 0)
 */
inline constexpr long long lowbit(long long a) {
    assert(a >= 0);
    return a & -a;
}
/**
 * @brief a の i ビット目が立っているか
 */
inline constexpr bool test_bit(long long a, long long i) {
    assert(a >= 0 && 0 <= i && i < 63);
    return a >> i & 1;
}
/**
 * @brief a の i ビット目を 1 にした値
 */
inline constexpr long long set_bit(long long a, long long i) {
    assert(a >= 0 && 0 <= i && i < 63);
    return a | 1LL << i;
}
/**
 * @brief a の i ビット目を 0 にした値
 */
inline constexpr long long reset_bit(long long a, long long i) {
    assert(a >= 0 && 0 <= i && i < 63);
    return a & ~(1LL << i);
}
/**
 * @brief a の i ビット目を反転した値
 */
inline constexpr long long flip_bit(long long a, long long i) {
    assert(a >= 0 && 0 <= i && i < 63);
    return a ^ 1LL << i;
}
/**
 * @brief 立っているビットの数の偶奇 (popcount(a) % 2)
 */
inline constexpr long long parity(long long a) { return popcount(a) & 1; }
/**
 * @brief long long を n 桁の 2 進数の文字列にする (btoll の逆)
 * n を省略すると bit_width(a) 桁 (0 なら "0")
 */
inline std::string lltob(long long a, long long n = -1, char one = '1', char zero = '0') {
    assert(a >= 0);
    if (n < 0) n = a == 0 ? 1 : bit_width(a);
    assert(n >= bit_width(a));
    std::string res(n, zero);
    for (long long i = 0; i < n && i < 63; i++) {
        if (a >> i & 1) res[n - 1 - i] = one;
    }
    return res;
}
/**
 * @brief 下位 n ビットの並びを逆にする (a < 2^n)
 */
inline constexpr long long reverse_bits(long long a, long long n) {
    assert(0 <= n && n <= 63 && 0 <= a && bit_width(a) <= n);
    long long res = 0;
    for (long long i = 0; i < n; i++) {
        if (a >> i & 1) res |= 1LL << (n - 1 - i);
    }
    return res;
}
/**
 * @brief 下位 n ビットを左に k ビット巡回シフトする (a < 2^n、k は負でもよい)
 */
inline constexpr long long rotate_left(long long a, long long k, long long n) {
    assert(1 <= n && n <= 63 && 0 <= a && bit_width(a) <= n);
    k %= n;
    if (k < 0) k += n;
    if (k == 0) return a;
    unsigned long long full = (1ULL << n) - 1;
    return static_cast<long long>((static_cast<unsigned long long>(a) << k & full) | static_cast<unsigned long long>(a) >> (n - k));
}
/**
 * @brief 下位 n ビットを右に k ビット巡回シフトする (a < 2^n、k は負でもよい)
 */
inline constexpr long long rotate_right(long long a, long long k, long long n) {
    assert(1 <= n && n <= 63);
    return rotate_left(a, -(k % n), n);
}
/**
 * @brief グレイコード (隣り合う値で 1 ビットだけ変わる) a ^ (a >> 1)
 */
inline constexpr long long gray_code(long long a) {
    assert(a >= 0);
    return a ^ a >> 1;
}
/**
 * @brief グレイコードから元の値に戻す (gray_code の逆)
 */
inline constexpr long long inverse_gray_code(long long g) {
    assert(g >= 0);
    for (long long s = 1; s < 64; s <<= 1) g ^= g >> s;
    return g;
}
/**
 * @brief mask の立っているビットのうち、下から k 番目 (0-indexed) の位置 O(log 64)
 */
inline constexpr long long kth_set_bit(long long mask, long long k) {
    assert(mask >= 0 && 0 <= k && k < popcount(mask));
    long long res = 0;
    for (long long w = 32; w > 0; w >>= 1) {
        // 下位 w ビットに立っているビットの数で、答えが上下どちらにあるかを決める
        long long c = popcount(mask & ((1LL << w) - 1));
        if (k >= c) {
            k -= c;
            mask >>= w;
            res += w;
        }
    }
    return res;
}
/**
 * @brief 0 ^ 1 ^ ... ^ n
 */
inline constexpr long long xor_upto(long long n) {
    assert(n >= 0);
    // 4 つごとに周期的になる
    long long r = n & 3;
    // r ごとの値の表として読めるように 1 行で書いているので整形しない
    // clang-format off
    return r == 0 ? n : r == 1 ? 1 : r == 2 ? n + 1 : 0;
    // clang-format on
}
/**
 * @brief 0 以上 n 以下の整数のうち、i ビット目が立っているものの数
 */
inline constexpr long long bit_count_upto(long long n, long long i) {
    assert(0 <= n && n < 0x7fffffffffffffffLL && 0 <= i && i < 63);
    // 2^(i + 1) ごとに、後半の 2^i 個で立つ
    unsigned long long m = static_cast<unsigned long long>(n) + 1, half = 1ULL << i, cycle = half << 1;
    unsigned long long r = m % cycle;
    return static_cast<long long>(m / cycle * half + (r > half ? r - half : 0));
}

namespace internal_bit {
// 範囲 for で使う列挙。next で次の値に進み、done になったら終わる
template <class Next>
struct BitEnumeration {
    long long first;
    bool empty;
    Next next;  // next(s) は次の値、終わりなら -1
    struct iterator {
        using value_type = long long;
        using difference_type = std::ptrdiff_t;
        using pointer = void;
        using reference = value_type;
        using iterator_category = std::input_iterator_tag;
        using iterator_concept = std::forward_iterator_tag;

        long long s = -1;
        const Next* next = nullptr;
        constexpr long long operator*() const { return s; }
        constexpr iterator& operator++() {
            s = (*next)(s);
            return *this;
        }
        constexpr iterator operator++(int) {
            auto previous = *this;
            ++*this;
            return previous;
        }
        constexpr bool operator!=(const iterator& other) const { return s != other.s; }
        constexpr bool operator==(const iterator& other) const { return s == other.s; }
    };
    constexpr iterator begin() const { return {empty ? -1 : first, &next}; }
    constexpr iterator end() const { return {-1, &next}; }
};
struct Bits {
    long long mask;
    struct iterator {
        using value_type = long long;
        using difference_type = std::ptrdiff_t;
        using pointer = void;
        using reference = value_type;
        using iterator_category = std::input_iterator_tag;
        using iterator_concept = std::forward_iterator_tag;

        long long s = 0;
        constexpr long long operator*() const { return countr_zero(s); }
        constexpr iterator& operator++() {
            s &= s - 1;
            return *this;
        }
        constexpr iterator operator++(int) {
            auto previous = *this;
            ++*this;
            return previous;
        }
        constexpr bool operator!=(const iterator& other) const { return s != other.s; }
        constexpr bool operator==(const iterator& other) const { return s == other.s; }
    };
    constexpr iterator begin() const { return {mask}; }
    constexpr iterator end() const { return {0}; }
};

struct SubsetPairs {
    long long n;
    struct iterator {
        using value_type = std::pair<long long, long long>;
        using difference_type = std::ptrdiff_t;
        using pointer = void;
        using reference = value_type;
        using iterator_category = std::input_iterator_tag;
        using iterator_concept = std::forward_iterator_tag;

        long long s = 0, t = 0;
        constexpr std::pair<long long, long long> operator*() const { return {s, t}; }
        constexpr iterator& operator++() {
            if (t == 0) {
                t = ++s;
            } else {
                t = (t - 1) & s;
            }
            return *this;
        }
        constexpr iterator operator++(int) {
            auto previous = *this;
            ++*this;
            return previous;
        }
        constexpr bool operator!=(const iterator& other) const { return s != other.s || t != other.t; }
        constexpr bool operator==(const iterator& other) const { return s == other.s && t == other.t; }
    };
    constexpr iterator begin() const { return {0, 0}; }
    constexpr iterator end() const { return {1LL << n, 1LL << n}; }
};

struct SubsetsNext {
    long long mask;
    constexpr long long operator()(long long s) const { return s == 0 ? -1 : (s - 1) & mask; }
};
struct SupersetsNext {
    long long mask, full;
    constexpr long long operator()(long long s) const { return s == full ? -1 : (s + 1) | mask; }
};
struct CombinationsNext {
    long long limit;
    constexpr long long operator()(long long s) const;
};
struct FixedSubsetsNext {
    long long mask, k;
    constexpr long long lowest(long long count) const {
        long long res = 0, rest = mask;
        for (long long j = 0; j < count; j++) {
            res |= rest & -rest;
            rest &= rest - 1;
        }
        return res;
    }
    constexpr long long operator()(long long s) const {
        if (s == 0) return -1;
        // mask の外のビットを 1 とみなして最下位ビットを足すと、繰り上がりが mask の中だけを進む。
        unsigned long long c = s & -s, r = ((static_cast<unsigned long long>(s) | ~static_cast<unsigned long long>(mask)) + c) & static_cast<unsigned long long>(mask);
        if (r == 0) return -1;
        return static_cast<long long>(r) | lowest(k - popcount(static_cast<long long>(r)));
    }
};

template <class Next>
constexpr BitEnumeration<Next> make_bit_enumeration(long long first, bool empty, Next next) {
    return {first, empty, next};
}
}  // namespace internal_bit

/**
 * @brief mask の部分集合を mask から 0 まで降順に列挙する (0 と mask を含む) 全体で O(2^popcount(mask))
 */
inline constexpr auto subsets(long long mask) {
    assert(mask >= 0);
    return internal_bit::make_bit_enumeration(mask, false, internal_bit::SubsetsNext{mask});
}
/**
 * @brief n ビットの集合のうち mask を含むものを mask から昇順に列挙する (mask と 2^n - 1 を含む) 全体で O(2^(n - popcount(mask)))
 */
inline constexpr auto supersets(long long mask, long long n) {
    assert(0 <= n && n <= 62 && 0 <= mask && mask < (1LL << n));
    long long full = (1LL << n) - 1;
    return internal_bit::make_bit_enumeration(mask, false, internal_bit::SupersetsNext{mask, full});
}
/**
 * @brief mask の立っているビットの位置を昇順に列挙する 全体で O(popcount(mask))
 */
inline constexpr auto bits(long long mask) {
    assert(mask >= 0);
    // 内部では残りのビットを持ち、* で最下位ビットの位置を返す
    return internal_bit::Bits{mask};
}
/**
 * @brief s と立っているビットの数が同じで、s より大きい最小の値 (Gosper's hack)
 * long long に収まらなければ -1
 */
inline constexpr long long next_combination_mask(long long s) {
    assert(s > 0);
    unsigned long long u = s, c = u & -u, r = u + c;
    unsigned long long t = (((r ^ u) >> 2) / c) | r;
    return t > 0x7fffffffffffffffULL ? -1 : static_cast<long long>(t);
}
constexpr long long internal_bit::CombinationsNext::operator()(long long s) const {
    if (s == 0) return -1;
    long long t = next_combination_mask(s);
    return t >= limit ? -1 : t;
}

/**
 * @brief n ビットの集合のうち、ちょうど k 個のビットが立つものを昇順に列挙する (Gosper's hack) 全体で O(C(n, k))
 * k > n なら何も列挙しない
 */
inline constexpr auto combinations_mask(long long n, long long k) {
    assert(0 <= n && n <= 62 && 0 <= k);
    long long limit = 1LL << n;
    return internal_bit::make_bit_enumeration(k > n ? -1 : (1LL << k) - 1, k > n, internal_bit::CombinationsNext{limit});
}
/**
 * @brief mask の部分集合のうち、ちょうど k 個のビットが立つものを昇順に列挙する 1 つあたり O(k)
 * k > popcount(mask) なら何も列挙しない
 */
inline constexpr auto subsets_of_size(long long mask, long long k) {
    assert(mask >= 0 && 0 <= k);
    const internal_bit::FixedSubsetsNext next{mask, k};
    bool empty = k > popcount(mask);
    return internal_bit::make_bit_enumeration(empty ? -1 : next.lowest(k), empty, next);
}

namespace internal_bit {
// rest の立っているビット i を昇順に、(i, mask ^ (1 << i)) の組で列挙する
struct ToggleOneBit {
    long long mask, rest;
    struct iterator {
        using value_type = std::pair<long long, long long>;
        using difference_type = std::ptrdiff_t;
        using pointer = void;
        using reference = value_type;
        using iterator_category = std::input_iterator_tag;
        using iterator_concept = std::forward_iterator_tag;

        long long mask = 0, s = 0;
        constexpr std::pair<long long, long long> operator*() const {
            long long i = countr_zero(s);
            return {i, mask ^ (1LL << i)};
        }
        constexpr iterator& operator++() {
            s &= s - 1;
            return *this;
        }
        constexpr iterator operator++(int) {
            auto previous = *this;
            ++*this;
            return previous;
        }
        constexpr bool operator!=(const iterator& other) const { return s != other.s; }
        constexpr bool operator==(const iterator& other) const { return s == other.s; }
    };
    constexpr iterator begin() const { return {mask, rest}; }
    constexpr iterator end() const { return {mask, 0}; }
};
}  // namespace internal_bit

/**
 * @brief n ビットのうち mask に含まれない位置 i を昇順に、(i, mask | (1 << i)) の組で列挙する 全体で O(n - popcount(mask))
 * bit DP で 1 つ要素を足す遷移に使う
 */
inline constexpr internal_bit::ToggleOneBit add_one(long long mask, long long n) {
    assert(0 <= n && n <= 62 && 0 <= mask && mask < (1LL << n));
    return {mask, ((1LL << n) - 1) ^ mask};
}
/**
 * @brief mask に含まれる位置 i を昇順に、(i, mask ^ (1 << i)) の組で列挙する 全体で O(popcount(mask))
 * bit DP で 1 つ要素を除いた集合から遷移するときに使う
 */
inline constexpr internal_bit::ToggleOneBit remove_one(long long mask) {
    assert(mask >= 0);
    return {mask, mask};
}

/**
 * @brief n ビットのすべての集合 S と、その部分集合 T の組 (S, T) を列挙する 全体で O(3^n)
 * S は 0 から昇順、各 S の中で T は S から 0 まで降順
 */
inline constexpr auto subset_pairs(long long n) {
    assert(0 <= n && n <= 62);
    return internal_bit::SubsetPairs{n};
}
#line 8 "test/unittest/utility/bit.test.cpp"

#include <algorithm>
#include <iostream>
#include <limits>
#include <random>
#line 14 "test/unittest/utility/bit.test.cpp"
#include <type_traits>
#line 16 "test/unittest/utility/bit.test.cpp"
#include <vector>
#if __cplusplus >= 202002L
#include <ranges>
#endif

bool ok = true;

void check(bool cond, const char* what) {
    if (!cond) {
        if (ok) std::cerr << "failed: " << what << std::endl;
        ok = false;
    }
}

int main() {
    std::mt19937_64 rng(314);

    for (int rep = 0; rep < 100000 && ok; rep++) {
        // 0 以上の long long (ビット数もばらつかせる)
        int width = rng() % 63 + 1;
        long long a = static_cast<long long>(rng() >> (64 - width));

        int pc = 0, clz = 0, ctz = 0;
        for (int i = 0; i < 63; i++) pc += a >> i & 1;
        for (int i = 63; i >= 0 && !(a >> i & 1); i--) clz++;
        for (int i = 0; i < 64 && !(a >> i & 1); i++) ctz++;
        check(popcount(a) == pc, "popcount");
        if (a > 0) {
            check(countl_zero(a) == clz, "countl_zero");
            check(countr_zero(a) == ctz, "countr_zero");
        }

        // btoll: 2 進数の文字列 (上位桁から)
        std::string s;
        for (int i = width - 1; i >= 0; i--) s += (a >> i & 1) ? '1' : '0';
        check(btoll(s) == a, "btoll");
        // 1 を表す文字を指定する
        std::string t = s;
        for (char& c : t) c = (c == '1') ? '#' : '.';
        check(btoll(t, '#') == a, "btoll(s, one)");

        // hamming_distance: ビットごとに比べる
        long long b = static_cast<long long>(rng() >> (64 - width));
        int hd = 0;
        for (int i = 0; i < 63; i++) hd += (a >> i & 1) != (b >> i & 1);
        check(hamming_distance(a, b) == hd, "hamming_distance");
    }

    // countl_one / countr_one / bit_width / bit_ceil / bit_floor を愚直な実装と比べる
    for (int rep = 0; rep < 100000 && ok; rep++) {
        int width = rng() % 64;
        long long a = width == 0 ? 0 : static_cast<long long>(rng() >> (64 - width));
        if (rep % 4 == 0) a = (1LL << (rng() % 63)) - rng() % 2;  // 2 の累乗とその前後
        if (a < 0) a = 0;
        int clo = 0, cto = 0, bw = 0;
        for (int i = 63; i >= 0 && (a >> i & 1); i--) clo++;
        for (int i = 0; i < 64 && (a >> i & 1); i++) cto++;
        for (int i = 0; i < 63; i++) {
            if (a >> i & 1) bw = i + 1;
        }
        long long ceil = 1, floor = 0;
        while (ceil < a && ceil <= (1LL << 61)) ceil *= 2;  // a > 2^62 なら使わない
        for (int i = 0; i < 63; i++) {
            if ((1LL << i) <= a) floor = 1LL << i;
        }
        check(countl_one(a) == clo, "countl_one");
        check(countr_one(a) == cto, "countr_one");
        check(bit_width(a) == bw, "bit_width");
        if (a <= (1LL << 62)) check(bit_ceil(a) == ceil, "bit_ceil");
        check(bit_floor(a) == floor, "bit_floor");
    }

    // 1 ビットの操作・位置・変換を愚直な実装と比べる
    for (int rep = 0; rep < 100000 && ok; rep++) {
        int width = rng() % 64;
        long long a = width == 0 ? 0 : static_cast<long long>(rng() >> (64 - width));
        if (rep % 4 == 0) a = 1LL << (rng() % 63);
        int top = -1, low = -1, pc = 0;
        for (int i = 0; i < 63; i++) {
            if (a >> i & 1) {
                top = i;
                if (low < 0) low = i;
                pc++;
            }
        }
        check(has_single_bit(a) == (pc == 1), "has_single_bit");
        check(msb(a) == top && lsb(a) == low, "msb / lsb");
        check(lowbit(a) == (low < 0 ? 0 : 1LL << low), "lowbit");
        check(parity(a) == pc % 2, "parity");
        long long i = rng() % 63;
        bool on = a >> i & 1;
        check(test_bit(a, i) == on, "test_bit");
        check(set_bit(a, i) == (on ? a : a + (1LL << i)), "set_bit");
        check(reset_bit(a, i) == (on ? a - (1LL << i) : a), "reset_bit");
        check(flip_bit(a, i) == (on ? a - (1LL << i) : a + (1LL << i)), "flip_bit");

        // lltob: 桁数を省略すると先頭に 0 を付けない
        std::string s;
        for (int j = std::max(top, 0); j >= 0; j--) s += (a >> j & 1) ? '1' : '0';
        check(lltob(a) == s && btoll(lltob(a)) == a, "lltob");
        long long n = std::max(top + 1, 0) + rng() % 3;
        if (n > 63) n = 63;
        if (n == 0) n = 1;
        check(lltob(a, n) == std::string(n - s.size(), '0') + s, "lltob(a, n)");
        std::string t = lltob(a, n, '#', '.');
        check(static_cast<long long>(t.size()) == n && btoll(t, '#') == a, "lltob(a, n, one, zero)");

        // reverse_bits / rotate_left / rotate_right: n ビットの各位置を動かす
        long long rev = 0, rl = 0, rr = 0, k = static_cast<long long>(rng() % 200) - 100;
        long long km = ((k % n) + n) % n;
        for (int j = 0; j < n; j++) {
            if (a >> j & 1) {
                rev |= 1LL << (n - 1 - j);
                rl |= 1LL << ((j + km) % n);
                rr |= 1LL << ((j - km + n) % n);
            }
        }
        check(reverse_bits(a, n) == rev, "reverse_bits");
        check(rotate_left(a, k, n) == rl, "rotate_left");
        check(rotate_right(a, k, n) == rr, "rotate_right");

        // gray_code: 逆変換で戻り、隣り合う値で 1 ビットだけ変わる
        check(inverse_gray_code(gray_code(a)) == a, "inverse_gray_code");
        if (a < std::numeric_limits<long long>::max()) check(popcount(gray_code(a) ^ gray_code(a + 1)) == 1, "gray_code");

        // kth_set_bit
        if (pc > 0) {
            long long kk = rng() % pc, pos = -1;
            for (int j = 0, c = 0; j < 63; j++) {
                if (a >> j & 1) {
                    if (c == kk) pos = j;
                    c++;
                }
            }
            check(kth_set_bit(a, kk) == pos, "kth_set_bit");
        }
    }
    // xor_upto / bit_count_upto: 小さい n は 1 つずつ数える
    {
        long long x = 0;
        std::vector<long long> cnt(63, 0);
        for (long long n = 0; n < 5000 && ok; n++) {
            x ^= n;
            check(xor_upto(n) == x, "xor_upto");
            for (int i = 0; i < 63; i++) {
                cnt[i] += n >> i & 1;
                check(bit_count_upto(n, i) == cnt[i], "bit_count_upto");
            }
        }
        long long mx = std::numeric_limits<long long>::max();
        // 大きい n: bit_count_upto の和は 0..n の popcount の和で、0..n を 2 つに分けて数えても同じ
        for (int rep = 0; rep < 1000 && ok; rep++) {
            long long n = static_cast<long long>(rng() >> 1);
            if (n == mx) n--;
            long long m = static_cast<long long>(rng() % 1000);
            if (n < m) continue;
            for (int i = 0; i < 63; i++) {
                long long direct = 0;
                for (long long v = n - m + 1; v <= n; v++) direct += v >> i & 1;
                check(bit_count_upto(n, i) - (n - m < 0 ? 0 : bit_count_upto(n - m, i)) == direct, "bit_count_upto 大きい n");
            }
            long long xr = xor_upto(n - m);
            for (long long v = n - m + 1; v <= n; v++) xr ^= v;
            check(xor_upto(n) == xr, "xor_upto 大きい n");
        }
        check(bit_count_upto(mx - 1, 62) == mx - (1LL << 62), "bit_count_upto 上限");
        check(xor_upto(0) == 0 && xor_upto(3) == 0 && xor_upto(mx - 1) == mx && xor_upto(mx) == 0, "xor_upto 境界");
    }

    // subsets / supersets / bits / combinations_mask / add_one / remove_one を、すべての値を調べる愚直な方法と比べる
    for (int rep = 0; rep < 300 && ok; rep++) {
        int n = rng() % 9;
        long long mask = static_cast<long long>(rng() % (1ULL << n));
        std::vector<long long> sub, sup, pos, got;
        for (long long s = (1LL << n) - 1; s >= 0; s--) {
            if ((s & mask) == s) sub.push_back(s);  // 降順
        }
        for (long long s = 0; s < (1LL << n); s++) {
            if ((s & mask) == mask) sup.push_back(s);  // 昇順
        }
        for (int i = 0; i < n; i++) {
            if (mask >> i & 1) pos.push_back(i);
        }
        got.clear();
        for (long long s : subsets(mask)) got.push_back(s);
        check(got == sub, "subsets");
        got.clear();
        for (long long s : supersets(mask, n)) got.push_back(s);
        check(got == sup, "supersets");
        got.clear();
        for (long long i : bits(mask)) got.push_back(i);
        check(got == pos, "bits");
        // add_one / remove_one: 1 つ足した (除いた) 集合と、その位置の組
        std::vector<std::pair<long long, long long>> add, rem, gp;
        for (int i = 0; i < n; i++) {
            if (mask >> i & 1)
                rem.emplace_back(i, mask ^ (1LL << i));
            else
                add.emplace_back(i, mask | (1LL << i));
        }
        for (auto [i, t] : add_one(mask, n)) gp.emplace_back(i, t);
        check(gp == add, "add_one");
        gp.clear();
        for (auto [i, t] : remove_one(mask)) gp.emplace_back(i, t);
        check(gp == rem, "remove_one");
        // subsets_of_size: mask の部分集合で要素数 k のもの (昇順)
        for (int k = 0; k <= n + 1; k++) {
            std::vector<long long> want;
            for (long long s = 0; s < (1LL << n); s++) {
                if ((s & mask) == s && __builtin_popcountll(s) == k) want.push_back(s);
            }
            got.clear();
            for (long long s : subsets_of_size(mask, k)) got.push_back(s);
            check(got == want, "subsets_of_size");
        }
        // next_combination_mask: 立っているビットの数が同じで次に大きい値
        if (mask > 0) {
            long long want = -1;
            for (long long s = mask + 1; s < (1LL << 12); s++) {
                if (__builtin_popcountll(s) == __builtin_popcountll(mask)) {
                    want = s;
                    break;
                }
            }
            check(next_combination_mask(mask) == want, "next_combination_mask");
        }
        for (int k = 0; k <= n + 1; k++) {
            std::vector<long long> comb;
            for (long long s = 0; s < (1LL << n); s++) {
                if (__builtin_popcountll(s) == k) comb.push_back(s);
            }
            got.clear();
            for (long long s : combinations_mask(n, k)) got.push_back(s);
            check(got == comb, "combinations_mask");
        }
    }
    {
        // 大きいビット幅と境界
        long long cnt = 0, last = -1;
        for (long long s : combinations_mask(62, 61)) cnt++, last = s;
        check(cnt == 62 && last == (1LL << 62) - 2, "combinations_mask(62, 61)");
        cnt = 0;
        for (long long s : supersets((1LL << 62) - 2, 62)) cnt += s;
        check(cnt == 2 * ((1LL << 62) - 2) + 1, "supersets 62 ビット");
        std::vector<long long> got;
        for (long long i : bits(std::numeric_limits<long long>::max())) got.push_back(i);
        check(static_cast<long long>(got.size()) == 63 && got.back() == 62, "bits(最大値)");
        got.clear();
        for (long long s : subsets(0)) got.push_back(s);
        check(got == std::vector<long long>{0}, "subsets(0)");
        // constexpr でも使える
        constexpr long long sum = [] {
            long long r = 0;
            for (long long s : subsets(0b1011)) r += s;
            for (long long i : bits(0b1011)) r += i;
            return r;
        }();
        static_assert(sum == 44 + 4);
        constexpr long long sum2 = [] {
            long long r = 0;
            for (auto [i, t] : add_one(0b0101, 4)) r += i * 100 + t;  // (1, 0111), (3, 1101)
            for (auto [i, t] : remove_one(0b0101)) r += i * 100 + t;  // (0, 0100), (2, 0001)
            return r;
        }();
        static_assert(sum2 == (100 + 7) + (300 + 13) + (0 + 4) + (200 + 1));
        got.clear();
        for (auto [i, t] : add_one((1LL << 62) - 2, 62)) got.push_back(i), got.push_back(t);
        check(got == std::vector<long long>{0, (1LL << 62) - 1}, "add_one 62 ビット");
    }

    {
        // subset_pairs: すべての (S, T ⊆ S) を S の昇順、T の降順に
        for (int n = 0; n <= 6 && ok; n++) {
            std::vector<std::pair<long long, long long>> want, gp;
            for (long long s = 0; s < (1LL << n); s++) {
                for (long long t = s; t >= 0; t--) {
                    if ((t & s) == t) want.emplace_back(s, t);
                }
            }
            for (auto [s, t] : subset_pairs(n)) gp.emplace_back(s, t);
            check(gp == want, "subset_pairs");
        }
        // 大きいビット幅と境界
        long long mx = std::numeric_limits<long long>::max();
        check(next_combination_mask(mx) == -1 && next_combination_mask(1LL << 62) == -1, "next_combination_mask 上限");
        check(next_combination_mask((1LL << 62) - 2) == (1LL << 62) + (1LL << 60) - 1, "next_combination_mask 62 ビット");
        std::vector<long long> got;
        for (long long s : subsets_of_size(mx, 62)) got.push_back(s);
        check(static_cast<long long>(got.size()) == 63 && got.front() == (1LL << 62) - 1 && got.back() == mx - 1, "subsets_of_size 63 ビット");
        got.clear();
        for (long long s : subsets_of_size(0b1010, 0)) got.push_back(s);
        check(got == std::vector<long long>{0}, "subsets_of_size(k = 0)");
        check(rotate_left(1, 1, 63) == 2 && rotate_left(1LL << 62, 1, 63) == 1 && rotate_right(1, 1, 63) == (1LL << 62), "rotate 63 ビット");
        check(reverse_bits(1, 63) == (1LL << 62) && inverse_gray_code(gray_code(mx)) == mx, "63 ビット");
        check(kth_set_bit(mx, 62) == 62 && kth_set_bit(1LL << 62, 0) == 62, "kth_set_bit 63 ビット");
        check(lltob(0) == "0" && lltob(5) == "101" && lltob(5, 5) == "00101" && lltob(0, 3, '#', '.') == "...", "lltob 決まった値");
        check(msb(0) == -1 && lsb(0) == -1 && lowbit(0) == 0 && msb(mx) == 62, "msb / lsb / lowbit 境界");
        constexpr long long sum = [] {
            long long r = 0;
            for (long long s : subsets_of_size(0b1101, 2)) r += s;  // 0101, 1001, 1100
            for (auto [s, t] : subset_pairs(2)) r += s * 10 + t;    // 3^2 = 9 組
            return r;
        }();
        static_assert(sum == (5 + 9 + 12) + (0 + 11 + 10 + 22 + 20 + 33 + 32 + 31 + 30));
        static_assert(has_single_bit(64) && !has_single_bit(0) && !has_single_bit(6));
        static_assert(gray_code(5) == 7 && inverse_gray_code(7) == 5 && rotate_left(0b0011, 3, 4) == 0b1001);
    }

    {
        auto verify_range = [&](auto range, const auto& expected) {
            using Value = decltype(*range.begin());
            check(std::vector<Value>(range.begin(), range.end()) == expected, "iterator range constructor");
            auto it = range.begin(), independent = it;
            decltype(it) assigned;
            assigned = it;
            if (it != range.end()) {
                const auto first = *it++;
                check(first == *independent && first == *assigned, "copy / postfix increment");
                ++independent;
                check(it == independent, "independent iterators");
            }
#if __cplusplus >= 202002L
            static_assert(std::ranges::forward_range<decltype(range)>);
            static_assert(std::ranges::viewable_range<decltype(range)>);
            auto selected = std::move(range) | std::views::filter([](const auto&) { return true; });
            std::vector<Value> actual;
            std::ranges::copy(selected, std::back_inserter(actual));
            check(actual == expected, "rvalue range / views::filter");
#endif
        };
        verify_range(subsets(5), std::vector<long long>{5, 4, 1, 0});
        verify_range(supersets(1, 3), std::vector<long long>{1, 3, 5, 7});
        verify_range(bits(5), std::vector<long long>{0, 2});
        verify_range(bits(0), std::vector<long long>{});
        verify_range(combinations_mask(3, 2), std::vector<long long>{3, 5, 6});
        verify_range(combinations_mask(2, 3), std::vector<long long>{});
        verify_range(subsets_of_size(5, 1), std::vector<long long>{1, 4});
        verify_range(add_one(1, 3), std::vector<std::pair<long long, long long>>{{1, 3}, {2, 5}});
        verify_range(remove_one(5), std::vector<std::pair<long long, long long>>{{0, 4}, {2, 1}});
        verify_range(subset_pairs(1), std::vector<std::pair<long long, long long>>{{0, 0}, {1, 1}, {1, 0}});
    }

    // 0 のときは C++20 の <bit> と同じ値
    check(countl_zero(0) == 64 && countr_zero(0) == 64, "countl_zero / countr_zero(0)");
    check(countl_one(0) == 0 && countr_one(0) == 0, "countl_one / countr_one(0)");
    check(bit_width(0) == 0 && bit_ceil(0) == 1 && bit_floor(0) == 0, "bit_width / bit_ceil / bit_floor(0)");
    check(bit_ceil(1LL << 62) == (1LL << 62) && bit_ceil((1LL << 61) + 1) == (1LL << 62), "bit_ceil 上限");
    check(countr_one(std::numeric_limits<long long>::max()) == 63 && bit_width(std::numeric_limits<long long>::max()) == 63, "最大値");

    // 戻り値の型は C++17 でも C++20 でも long long
    static_assert(std::is_same_v<decltype(popcount(1)), long long>);
    static_assert(std::is_same_v<decltype(countl_zero(1)), long long>);
    static_assert(std::is_same_v<decltype(countr_zero(1)), long long>);
    static_assert(std::is_same_v<decltype(countl_one(1)), long long>);
    static_assert(std::is_same_v<decltype(countr_one(1)), long long>);
    static_assert(std::is_same_v<decltype(bit_width(1)), long long>);
    static_assert(std::is_same_v<decltype(bit_ceil(1)), long long>);
    static_assert(std::is_same_v<decltype(bit_floor(1)), long long>);
    static_assert(bit_width(5) == 3 && bit_ceil(5) == 8 && bit_floor(5) == 4 && countl_zero(0) == 64);

    // 決まった値
    check(popcount(0) == 0 && popcount((1LL << 62) - 1) == 62, "popcount 境界");
    check(countl_zero(1) == 63 && countr_zero(1LL << 62) == 62, "countl_zero / countr_zero 境界");
    check(hamming_distance(5, 3) == 2 && hamming_distance(7, 7) == 0, "hamming_distance 決まった値");
    check(btoll("") == 0 && btoll("0") == 0 && btoll("101") == 5, "btoll 決まった値");

    if (ok) std::cout << "Hello World" << std::endl;
}
Back to top page