m1une's library

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

View on GitHub

:heavy_check_mark: verify/ds/binary_trie/binary_trie_monoid.test.cpp

Depends on

Code

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

#include "../../../ds/binary_trie/binary_trie_monoid.hpp"
#include "../../../monoid/add.hpp"
#include "../../../monoid/mul.hpp"

#include <algorithm>
#include <cassert>
#include <cstdint>
#include "../../../utilities/fast_io.hpp"
#include <utility>
#include <vector>

void basic_test() {
    using Product = m1une::monoid::Mul<long long>;
    using ProductTrie =
        m1une::ds::BinaryTrieMonoid<Product, std::uint32_t, 10>;

    ProductTrie product;
    product.reserve(64);
    const auto one_node = product.insert(1, 2);
    product.insert(2, 3);
    product.insert(7, 5);
    const auto seven_node = product.insert(7, 11);

    assert(product.root() == 0);
    assert(product.find(1) == one_node);
    assert(product.find(7) == seven_node);
    assert(product.find(6) == ProductTrie::null_node);
    assert(product.node(product.root()).count == 4);
    assert(product.node(product.root()).prod == 330);
    assert(product.node(seven_node).count == 2);
    assert(product.node(seven_node).prod == 55);
    assert(product.node_count() == 1 + 10 + 2 + 3);
    assert(product.size() == 4);
    assert(product.count(7) == 2);
    assert(product.prod(7) == 55);
    assert(product.kth(0) == 1);
    assert(product.kth(2) == 7);
    assert(product.min() == 1);
    assert(product.max() == 7);
    assert(product.kth_xor(0, 3) == 1);
    assert(product.kth_xor(2, 3) == 4);
    assert(product.min_xor(3) == 1);
    assert(product.max_xor(3) == 4);
    assert(product.count_xor_equal(3, 4) == 2);
    assert(product.prod_xor_less(3, 4) == 6);
    assert(product.count_xor_less(3, 4) == 2);
    assert(product.count_less_xor(3, 4) == 2);
    assert(product.count_xor_less_equal(3, 4) == 4);
    assert(product.count_xor_greater(3, 2) == 2);
    assert(product.count_xor_greater_equal(3, 2) == 3);
    assert(product.count_xor_range(3, 2, 5) == 3);
    assert(product.prod_xor_equal(3, 4) == 55);
    assert(product.prod_xor_less_equal(3, 4) == 330);
    assert(product.prod_xor_greater(3, 2) == 55);
    assert(product.prod_xor_greater_equal(3, 2) == 110);
    assert(product.prod_xor_range(3, 2, 5) == 110);
    assert(product.prod_xor_less(3, 0) == 1);
    assert(product.prod_xor_less(0, 1024) == 330);
    assert(product.prod_xor_range(3, 2, 1024) == 110);
    assert(product.order_of_key(7) == 2);
    assert(product.count_less(7) == 2);
    assert(product.count_less_equal(7) == 4);
    assert(product.count_greater(2) == 2);
    assert(product.count_greater_equal(2) == 3);
    assert(product.count_range(2, 7) == 1);
    assert(product.prod_less(7) == 6);
    assert(product.prod_less_equal(7) == 330);
    assert(product.prod_greater(2) == 55);
    assert(product.prod_greater_equal(2) == 165);
    assert(product.prod_range(2, 7) == 3);

    product.xor_all(6);
    assert(product.xor_mask() == 6);
    assert(product.find(7 ^ 6) == seven_node);
    assert(product.prod(7 ^ 6) == 55);
    assert(product.prod_xor_less(5, 4) == 6);
    assert(product.erase_all(7 ^ 6) == 2);
    assert(product.all_prod() == 6);
    product.clear();
    assert(product.empty());
    assert(product.node_count() == 1);
    assert(product.xor_mask() == 0);

    std::vector<std::pair<std::uint32_t, long long>> entries;
    entries.emplace_back(4, 2);
    entries.emplace_back(9, 3);
    ProductTrie from_range(entries.begin(), entries.end());
    assert(from_range.all_prod() == 6);
}

void randomized_test() {
    using Sum = m1une::monoid::Add<long long>;
    using SumTrie =
        m1une::ds::BinaryTrieMonoid<Sum, std::uint32_t, 10>;

    SumTrie trie;
    std::vector<std::pair<std::uint32_t, long long>> entries;
    std::uint64_t seed = 123456789;

    for (int query = 0; query < 10000; ++query) {
        seed = seed * 6364136223846793005ULL +
               1442695040888963407ULL;
        const std::uint32_t key = std::uint32_t(seed >> 32) & 1023U;
        const std::uint32_t value = std::uint32_t(seed) & 1023U;
        const int type = int(seed % 6);

        if (type <= 1) {
            trie.insert(key, value);
            entries.emplace_back(key, value);
        } else if (type == 2) {
            trie.xor_all(key);
            for (auto& entry : entries) entry.first ^= key;
        } else if (type == 3) {
            int expected_erased = 0;
            for (const auto& entry : entries) {
                if (entry.first == key) ++expected_erased;
            }
            assert(trie.erase_all(key) == expected_erased);
            entries.erase(
                std::remove_if(
                    entries.begin(), entries.end(),
                    [&](const auto& entry) {
                        return entry.first == key;
                    }),
                entries.end());
        } else if (type == 4) {
            int expected_count = 0;
            long long expected_prod = 0;
            for (const auto& entry : entries) {
                if (entry.first == key) {
                    ++expected_count;
                    expected_prod += entry.second;
                }
            }
            assert(trie.count(key) == expected_count);
            assert(trie.prod(key) == expected_prod);
        } else {
            const std::uint32_t upper = std::uint32_t(seed >> 20) & 1023U;
            const std::uint32_t target = std::uint32_t(seed >> 12) & 1023U;
            const std::uint32_t other = std::uint32_t(seed >> 4) & 1023U;
            const std::uint32_t lower = std::min(upper, other);
            const std::uint32_t range_upper =
                std::max(upper, other) + 1;
            int expected_count = 0;
            long long expected_prod = 0;
            int expected_equal_count = 0;
            long long expected_equal_prod = 0;
            int expected_less_equal_count = 0;
            long long expected_less_equal_prod = 0;
            int expected_greater_count = 0;
            long long expected_greater_prod = 0;
            int expected_greater_equal_count = 0;
            long long expected_greater_equal_prod = 0;
            int expected_range_count = 0;
            long long expected_range_prod = 0;
            std::vector<std::uint32_t> xor_values;
            xor_values.reserve(entries.size());
            for (const auto& entry : entries) {
                const std::uint32_t xor_value = entry.first ^ key;
                xor_values.push_back(xor_value);
                if (xor_value == target) {
                    ++expected_equal_count;
                    expected_equal_prod += entry.second;
                }
                if (xor_value < upper) {
                    ++expected_count;
                    expected_prod += entry.second;
                }
                if (xor_value <= upper) {
                    ++expected_less_equal_count;
                    expected_less_equal_prod += entry.second;
                }
                if (xor_value > upper) {
                    ++expected_greater_count;
                    expected_greater_prod += entry.second;
                }
                if (xor_value >= upper) {
                    ++expected_greater_equal_count;
                    expected_greater_equal_prod += entry.second;
                }
                if (lower <= xor_value && xor_value < range_upper) {
                    ++expected_range_count;
                    expected_range_prod += entry.second;
                }
            }
            std::sort(xor_values.begin(), xor_values.end());

            assert(trie.count_xor_equal(key, target) ==
                   expected_equal_count);
            assert(trie.prod_xor_equal(key, target) ==
                   expected_equal_prod);
            assert(trie.count_xor_less(key, upper) == expected_count);
            assert(trie.count_less_xor(key, upper) == expected_count);
            assert(trie.prod_xor_less(key, upper) == expected_prod);
            assert(trie.count_xor_less_equal(key, upper) ==
                   expected_less_equal_count);
            assert(trie.prod_xor_less_equal(key, upper) ==
                   expected_less_equal_prod);
            assert(trie.count_xor_greater(key, upper) ==
                   expected_greater_count);
            assert(trie.prod_xor_greater(key, upper) ==
                   expected_greater_prod);
            assert(trie.count_xor_greater_equal(key, upper) ==
                   expected_greater_equal_count);
            assert(trie.prod_xor_greater_equal(key, upper) ==
                   expected_greater_equal_prod);
            assert(trie.count_xor_range(key, lower, range_upper) ==
                   expected_range_count);
            assert(trie.prod_xor_range(key, lower, range_upper) ==
                   expected_range_prod);

            if (!xor_values.empty()) {
                const int k = int(seed % xor_values.size());
                assert(trie.kth_xor(k, key) == xor_values[k]);
                assert(trie.min_xor(key) == xor_values.front());
                assert(trie.max_xor(key) == xor_values.back());
            }
        }

        assert(trie.size() == int(entries.size()));
        long long expected_all_prod = 0;
        for (const auto& entry : entries) {
            expected_all_prod += entry.second;
        }
        assert(trie.all_prod() == expected_all_prod);
    }
}

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

    basic_test();
    randomized_test();

    using Sum = m1une::monoid::Add<int>;
    m1une::ds::BinaryTrieMonoid<Sum, std::uint32_t, 30> trie;

    int q;
    fast_input >> q;
    while (q--) {
        int type;
        std::uint32_t value;
        fast_input >> type >> value;
        if (type == 0) {
            if (!trie.contains(value)) trie.insert(value, 0);
        } else if (type == 1) {
            trie.erase_all(value);
        } else {
            fast_output << trie.min_xor(value) << '\n';
        }
    }
}
#line 1 "verify/ds/binary_trie/binary_trie_monoid.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/set_xor_min"

#line 1 "ds/binary_trie/binary_trie_monoid.hpp"



#include <cassert>
#include <cstdint>
#include <initializer_list>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>

#line 1 "monoid/concept.hpp"



#include <concepts>

namespace m1une {
namespace monoid {

// Concept to check if a type satisfies the requirements of a Monoid.
// A Monoid must have a `value_type`, an identity element `id()`, and an associative binary operation `op()`.
template <typename M>
concept IsMonoid = requires(typename M::value_type a, typename M::value_type b) {
    // 1. Must define `value_type`
    typename M::value_type;

    // 2. Must have a static method `id()` returning `value_type`
    { M::id() } -> std::same_as<typename M::value_type>;

    // 3. Must have a static method `op(a, b)` returning `value_type`
    { M::op(a, b) } -> std::same_as<typename M::value_type>;
};

// Concept for groups. A type satisfying this concept must also obey the group
// laws; concepts can check the interface but not the algebraic properties.
template <typename M>
concept IsGroup = IsMonoid<M> && requires(typename M::value_type a) {
    { M::inv(a) } -> std::same_as<typename M::value_type>;
};

// Concept for commutative groups. Commutativity is a semantic requirement and
// cannot be checked by a C++ concept.
template <typename M>
concept IsCommutativeGroup = IsGroup<M>;

}  // namespace monoid
}  // namespace m1une


#line 13 "ds/binary_trie/binary_trie_monoid.hpp"

namespace m1une {
namespace ds {

template <m1une::monoid::IsMonoid Monoid,
          typename UInt = std::uint32_t,
          int BitWidth = std::numeric_limits<UInt>::digits>
struct BinaryTrieMonoid {
    using T = typename Monoid::value_type;

    static_assert(std::is_integral_v<UInt>);
    static_assert(std::is_unsigned_v<UInt>);
    static_assert(!std::is_same_v<UInt, bool>);
    static_assert(0 < BitWidth);
    static_assert(BitWidth <= std::numeric_limits<UInt>::digits);

    using node_id = int;
    static constexpr node_id null_node = -1;

    struct Node {
        node_id child[2];
        int count;
        T prod;

        Node() : child{null_node, null_node}, count(0), prod(Monoid::id()) {}
    };

   private:
    struct Aggregate {
        int count;
        T prod;
    };

    std::vector<Node> nodes;
    UInt lazy_xor;

    static constexpr int bit(UInt value, int position) {
        return int((value >> position) & UInt(1));
    }

    static constexpr UInt value_mask() {
        if constexpr (BitWidth == std::numeric_limits<UInt>::digits) {
            return std::numeric_limits<UInt>::max();
        } else {
            return (UInt(1) << BitWidth) - UInt(1);
        }
    }

    static constexpr bool valid_value(UInt value) {
        return (value & ~value_mask()) == UInt(0);
    }

    node_id new_node() {
        nodes.emplace_back();
        return int(nodes.size()) - 1;
    }

    int subtree_size(node_id node) const {
        return node == null_node ? 0 : nodes[node].count;
    }

    T subtree_prod(node_id node) const {
        return node == null_node ? Monoid::id() : nodes[node].prod;
    }

    void update(int node) {
        nodes[node].count =
            subtree_size(nodes[node].child[0]) +
            subtree_size(nodes[node].child[1]);
        nodes[node].prod =
            Monoid::op(subtree_prod(nodes[node].child[0]),
                       subtree_prod(nodes[node].child[1]));
    }

    node_id find_node(UInt key) const {
        key ^= lazy_xor;
        node_id node = 0;
        for (int position = BitWidth - 1; position >= 0; --position) {
            node = nodes[node].child[bit(key, position)];
            if (node == null_node || nodes[node].count == 0) {
                return null_node;
            }
        }
        return node;
    }

    static int extend_comparison(int relation,
                                 int digit,
                                 int bound_digit) {
        if (relation != 0) return relation;
        if (digit < bound_digit) return -1;
        if (digit > bound_digit) return 1;
        return 0;
    }

    Aggregate xor_range_impl(int node,
                             int position,
                             UInt effective_xor,
                             UInt lower,
                             UInt upper,
                             int lower_relation,
                             int upper_relation) const {
        if (node == -1 || nodes[node].count == 0 ||
            lower_relation < 0 || upper_relation > 0) {
            return {0, Monoid::id()};
        }
        if (lower_relation > 0 && upper_relation < 0) {
            return {nodes[node].count, nodes[node].prod};
        }
        if (position < 0) {
            if (lower_relation >= 0 && upper_relation < 0) {
                return {nodes[node].count, nodes[node].prod};
            }
            return {0, Monoid::id()};
        }

        Aggregate result{0, Monoid::id()};
        const int xor_digit = bit(effective_xor, position);
        const int lower_digit = bit(lower, position);
        const int upper_digit = bit(upper, position);
        for (int xor_result_digit = 0;
             xor_result_digit < 2;
             ++xor_result_digit) {
            const int direction = xor_result_digit ^ xor_digit;
            Aggregate part = xor_range_impl(
                nodes[node].child[direction],
                position - 1,
                effective_xor,
                lower,
                upper,
                extend_comparison(lower_relation,
                                  xor_result_digit,
                                  lower_digit),
                extend_comparison(upper_relation,
                                  xor_result_digit,
                                  upper_digit));
            result.count += part.count;
            result.prod = Monoid::op(result.prod, part.prod);
        }
        return result;
    }

    T prod_xor_greater_equal_impl(UInt value, UInt lower) const {
        const UInt effective_xor = lazy_xor ^ value;
        T result = Monoid::id();
        int node = 0;
        for (int position = BitWidth - 1;
             position >= 0 && node != -1;
             --position) {
            const int zero = bit(effective_xor, position);
            if (bit(lower, position) == 0) {
                result =
                    Monoid::op(result,
                               subtree_prod(nodes[node].child[zero ^ 1]));
                node = nodes[node].child[zero];
            } else {
                node = nodes[node].child[zero ^ 1];
            }
        }
        return Monoid::op(result, subtree_prod(node));
    }

   public:
    BinaryTrieMonoid() : nodes(1), lazy_xor(0) {}

    BinaryTrieMonoid(
        std::initializer_list<std::pair<UInt, T>> init)
        : BinaryTrieMonoid() {
        for (const auto& entry : init) {
            insert(entry.first, entry.second);
        }
    }

    template <typename Iterator>
    BinaryTrieMonoid(Iterator first, Iterator last)
        : BinaryTrieMonoid() {
        while (first != last) {
            insert(first->first, first->second);
            ++first;
        }
    }

    BinaryTrieMonoid(const std::vector<UInt>& keys,
                     const std::vector<T>& values)
        : BinaryTrieMonoid() {
        assert(keys.size() == values.size());
        for (int i = 0; i < int(keys.size()); ++i) {
            insert(keys[i], values[i]);
        }
    }

    int size() const {
        return nodes[0].count;
    }

    bool empty() const {
        return size() == 0;
    }

    node_id root() const {
        return 0;
    }

    const Node& node(node_id id) const {
        assert(0 <= id && std::size_t(id) < nodes.size());
        return nodes[id];
    }

    node_id find(UInt key) const {
        assert(valid_value(key));
        return find_node(key);
    }

    std::size_t node_count() const {
        return nodes.size();
    }

    void reserve(std::size_t node_capacity) {
        nodes.reserve(node_capacity);
    }

    UInt xor_mask() const {
        return lazy_xor;
    }

    void clear() {
        nodes.clear();
        nodes.emplace_back();
        lazy_xor = 0;
    }

    node_id insert(UInt key, const T& value) {
        assert(valid_value(key));
        key ^= lazy_xor;
        node_id node = 0;
        ++nodes[node].count;
        nodes[node].prod = Monoid::op(nodes[node].prod, value);
        for (int position = BitWidth - 1; position >= 0; --position) {
            const int direction = bit(key, position);
            if (nodes[node].child[direction] == null_node) {
                const node_id child = new_node();
                nodes[node].child[direction] = child;
            }
            node = nodes[node].child[direction];
            ++nodes[node].count;
            nodes[node].prod = Monoid::op(nodes[node].prod, value);
        }
        return node;
    }

    int count(UInt key) const {
        assert(valid_value(key));
        const node_id node = find_node(key);
        return node == null_node ? 0 : nodes[node].count;
    }

    bool contains(UInt key) const {
        return count(key) > 0;
    }

    T prod(UInt key) const {
        assert(valid_value(key));
        const node_id node = find_node(key);
        return node == null_node ? Monoid::id() : nodes[node].prod;
    }

    T all_prod() const {
        return nodes[0].prod;
    }

    int erase_all(UInt key) {
        assert(valid_value(key));
        key ^= lazy_xor;

        int path[BitWidth + 1];
        path[0] = 0;
        int node = 0;
        for (int position = BitWidth - 1, depth = 1;
             position >= 0;
             --position, ++depth) {
            node = nodes[node].child[bit(key, position)];
            if (node == -1 || nodes[node].count == 0) return 0;
            path[depth] = node;
        }

        const int erased = nodes[node].count;
        nodes[node].count = 0;
        nodes[node].prod = Monoid::id();
        for (int depth = BitWidth - 1; depth >= 0; --depth) {
            update(path[depth]);
        }
        return erased;
    }

    void xor_all(UInt value) {
        assert(valid_value(value));
        lazy_xor ^= value;
    }

    UInt kth_xor(int k, UInt value) const {
        assert(0 <= k && k < size());
        assert(valid_value(value));
        const UInt effective_xor = lazy_xor ^ value;
        UInt result = 0;
        int node = 0;
        for (int position = BitWidth - 1; position >= 0; --position) {
            const int preferred = bit(effective_xor, position);
            const int preferred_size =
                subtree_size(nodes[node].child[preferred]);
            if (k < preferred_size) {
                node = nodes[node].child[preferred];
            } else {
                k -= preferred_size;
                node = nodes[node].child[preferred ^ 1];
                result |= UInt(1) << position;
            }
        }
        return result;
    }

    UInt kth(int k) const {
        return kth_xor(k, 0);
    }

    UInt min() const {
        return kth(0);
    }

    UInt max() const {
        return kth(size() - 1);
    }

    UInt min_xor(UInt value) const {
        return kth_xor(0, value);
    }

    UInt max_xor(UInt value) const {
        return kth_xor(size() - 1, value);
    }

    int count_xor_equal(UInt value, UInt target) const {
        assert(valid_value(value));
        assert(valid_value(target));
        return count(value ^ target);
    }

    int count_xor_less(UInt value, UInt upper) const {
        assert(valid_value(value));
        if (!valid_value(upper)) return size();

        const UInt effective_xor = lazy_xor ^ value;
        int result = 0;
        int node = 0;
        for (int position = BitWidth - 1;
             position >= 0 && node != -1;
             --position) {
            const int zero = bit(effective_xor, position);
            if (bit(upper, position) == 1) {
                result += subtree_size(nodes[node].child[zero]);
                node = nodes[node].child[zero ^ 1];
            } else {
                node = nodes[node].child[zero];
            }
        }
        return result;
    }

    int count_less_xor(UInt value, UInt upper) const {
        return count_xor_less(value, upper);
    }

    int count_xor_less_equal(UInt value, UInt upper) const {
        assert(valid_value(value));
        assert(valid_value(upper));
        if (upper == value_mask()) return size();
        return count_xor_less(value, upper + UInt(1));
    }

    int count_xor_greater(UInt value, UInt lower) const {
        assert(valid_value(value));
        assert(valid_value(lower));
        return size() - count_xor_less_equal(value, lower);
    }

    int count_xor_greater_equal(UInt value, UInt lower) const {
        assert(valid_value(value));
        assert(valid_value(lower));
        return size() - count_xor_less(value, lower);
    }

    int count_xor_range(UInt value, UInt lower, UInt upper) const {
        assert(valid_value(value));
        assert(valid_value(lower));
        assert(lower <= upper);
        return count_xor_less(value, upper) -
               count_xor_less(value, lower);
    }

    int order_of_key(UInt key) const {
        return count_xor_less(0, key);
    }

    int count_less(UInt key) const {
        return order_of_key(key);
    }

    int count_less_equal(UInt key) const {
        return count_xor_less_equal(0, key);
    }

    int count_greater(UInt key) const {
        return count_xor_greater(0, key);
    }

    int count_greater_equal(UInt key) const {
        return count_xor_greater_equal(0, key);
    }

    int count_range(UInt lower, UInt upper) const {
        return count_xor_range(0, lower, upper);
    }

    T prod_xor_equal(UInt value, UInt target) const {
        assert(valid_value(value));
        assert(valid_value(target));
        return prod(value ^ target);
    }

    T prod_xor_less(UInt value, UInt upper) const {
        assert(valid_value(value));
        if (!valid_value(upper)) return all_prod();

        const UInt effective_xor = lazy_xor ^ value;
        T result = Monoid::id();
        int node = 0;
        for (int position = BitWidth - 1;
             position >= 0 && node != -1;
             --position) {
            const int zero = bit(effective_xor, position);
            if (bit(upper, position) == 1) {
                result =
                    Monoid::op(result,
                               subtree_prod(nodes[node].child[zero]));
                node = nodes[node].child[zero ^ 1];
            } else {
                node = nodes[node].child[zero];
            }
        }
        return result;
    }

    T prod_xor_less_equal(UInt value, UInt upper) const {
        assert(valid_value(value));
        assert(valid_value(upper));
        if (upper == value_mask()) return all_prod();
        return prod_xor_less(value, upper + UInt(1));
    }

    T prod_xor_greater(UInt value, UInt lower) const {
        assert(valid_value(value));
        assert(valid_value(lower));
        if (lower == value_mask()) return Monoid::id();
        return prod_xor_greater_equal_impl(value, lower + UInt(1));
    }

    T prod_xor_greater_equal(UInt value, UInt lower) const {
        assert(valid_value(value));
        assert(valid_value(lower));
        return prod_xor_greater_equal_impl(value, lower);
    }

    T prod_xor_range(UInt value, UInt lower, UInt upper) const {
        assert(valid_value(value));
        assert(valid_value(lower));
        assert(lower <= upper);
        if (lower == upper) return Monoid::id();
        if (!valid_value(upper)) {
            return prod_xor_greater_equal(value, lower);
        }
        return xor_range_impl(0,
                              BitWidth - 1,
                              lazy_xor ^ value,
                              lower,
                              upper,
                              0,
                              0)
            .prod;
    }

    T prod_less(UInt key) const {
        return prod_xor_less(0, key);
    }

    T prod_less_equal(UInt key) const {
        return prod_xor_less_equal(0, key);
    }

    T prod_greater(UInt key) const {
        return prod_xor_greater(0, key);
    }

    T prod_greater_equal(UInt key) const {
        return prod_xor_greater_equal(0, key);
    }

    T prod_range(UInt lower, UInt upper) const {
        return prod_xor_range(0, lower, upper);
    }
};

}  // namespace ds
}  // namespace m1une


#line 1 "monoid/add.hpp"



namespace m1une {
namespace monoid {

// Monoid for addition (Range Sum).
template <typename T>
struct Add {
    using value_type = T;
    static constexpr bool commutative = true;

    // Returns the identity element for addition, which is 0.
    static constexpr T id() {
        return T(0);
    }

    // Returns the sum of a and b.
    static constexpr T op(const T& a, const T& b) {
        return a + b;
    }

    static constexpr T inv(const T& x) {
        return -x;
    }
};

}  // namespace monoid
}  // namespace m1une


#line 1 "monoid/mul.hpp"



namespace m1une {
namespace monoid {

// Monoid for multiplication (Range Product).
template <typename T>
struct Mul {
    using value_type = T;
    static constexpr bool commutative = true;

    // Returns the identity element for multiplication, which is 1.
    static constexpr T id() {
        return T(1);
    }

    // Returns the product of a and b.
    static constexpr T op(const T& a, const T& b) {
        return a * b;
    }
};

}  // namespace monoid
}  // namespace m1une


#line 6 "verify/ds/binary_trie/binary_trie_monoid.test.cpp"

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



#line 5 "utilities/fast_io.hpp"
#include <array>
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#line 12 "utilities/fast_io.hpp"
#include <cstring>
#include <iterator>
#include <string>
#include <sys/stat.h>
#line 18 "utilities/fast_io.hpp"
#include <unistd.h>
#line 20 "utilities/fast_io.hpp"

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 13 "verify/ds/binary_trie/binary_trie_monoid.test.cpp"

void basic_test() {
    using Product = m1une::monoid::Mul<long long>;
    using ProductTrie =
        m1une::ds::BinaryTrieMonoid<Product, std::uint32_t, 10>;

    ProductTrie product;
    product.reserve(64);
    const auto one_node = product.insert(1, 2);
    product.insert(2, 3);
    product.insert(7, 5);
    const auto seven_node = product.insert(7, 11);

    assert(product.root() == 0);
    assert(product.find(1) == one_node);
    assert(product.find(7) == seven_node);
    assert(product.find(6) == ProductTrie::null_node);
    assert(product.node(product.root()).count == 4);
    assert(product.node(product.root()).prod == 330);
    assert(product.node(seven_node).count == 2);
    assert(product.node(seven_node).prod == 55);
    assert(product.node_count() == 1 + 10 + 2 + 3);
    assert(product.size() == 4);
    assert(product.count(7) == 2);
    assert(product.prod(7) == 55);
    assert(product.kth(0) == 1);
    assert(product.kth(2) == 7);
    assert(product.min() == 1);
    assert(product.max() == 7);
    assert(product.kth_xor(0, 3) == 1);
    assert(product.kth_xor(2, 3) == 4);
    assert(product.min_xor(3) == 1);
    assert(product.max_xor(3) == 4);
    assert(product.count_xor_equal(3, 4) == 2);
    assert(product.prod_xor_less(3, 4) == 6);
    assert(product.count_xor_less(3, 4) == 2);
    assert(product.count_less_xor(3, 4) == 2);
    assert(product.count_xor_less_equal(3, 4) == 4);
    assert(product.count_xor_greater(3, 2) == 2);
    assert(product.count_xor_greater_equal(3, 2) == 3);
    assert(product.count_xor_range(3, 2, 5) == 3);
    assert(product.prod_xor_equal(3, 4) == 55);
    assert(product.prod_xor_less_equal(3, 4) == 330);
    assert(product.prod_xor_greater(3, 2) == 55);
    assert(product.prod_xor_greater_equal(3, 2) == 110);
    assert(product.prod_xor_range(3, 2, 5) == 110);
    assert(product.prod_xor_less(3, 0) == 1);
    assert(product.prod_xor_less(0, 1024) == 330);
    assert(product.prod_xor_range(3, 2, 1024) == 110);
    assert(product.order_of_key(7) == 2);
    assert(product.count_less(7) == 2);
    assert(product.count_less_equal(7) == 4);
    assert(product.count_greater(2) == 2);
    assert(product.count_greater_equal(2) == 3);
    assert(product.count_range(2, 7) == 1);
    assert(product.prod_less(7) == 6);
    assert(product.prod_less_equal(7) == 330);
    assert(product.prod_greater(2) == 55);
    assert(product.prod_greater_equal(2) == 165);
    assert(product.prod_range(2, 7) == 3);

    product.xor_all(6);
    assert(product.xor_mask() == 6);
    assert(product.find(7 ^ 6) == seven_node);
    assert(product.prod(7 ^ 6) == 55);
    assert(product.prod_xor_less(5, 4) == 6);
    assert(product.erase_all(7 ^ 6) == 2);
    assert(product.all_prod() == 6);
    product.clear();
    assert(product.empty());
    assert(product.node_count() == 1);
    assert(product.xor_mask() == 0);

    std::vector<std::pair<std::uint32_t, long long>> entries;
    entries.emplace_back(4, 2);
    entries.emplace_back(9, 3);
    ProductTrie from_range(entries.begin(), entries.end());
    assert(from_range.all_prod() == 6);
}

void randomized_test() {
    using Sum = m1une::monoid::Add<long long>;
    using SumTrie =
        m1une::ds::BinaryTrieMonoid<Sum, std::uint32_t, 10>;

    SumTrie trie;
    std::vector<std::pair<std::uint32_t, long long>> entries;
    std::uint64_t seed = 123456789;

    for (int query = 0; query < 10000; ++query) {
        seed = seed * 6364136223846793005ULL +
               1442695040888963407ULL;
        const std::uint32_t key = std::uint32_t(seed >> 32) & 1023U;
        const std::uint32_t value = std::uint32_t(seed) & 1023U;
        const int type = int(seed % 6);

        if (type <= 1) {
            trie.insert(key, value);
            entries.emplace_back(key, value);
        } else if (type == 2) {
            trie.xor_all(key);
            for (auto& entry : entries) entry.first ^= key;
        } else if (type == 3) {
            int expected_erased = 0;
            for (const auto& entry : entries) {
                if (entry.first == key) ++expected_erased;
            }
            assert(trie.erase_all(key) == expected_erased);
            entries.erase(
                std::remove_if(
                    entries.begin(), entries.end(),
                    [&](const auto& entry) {
                        return entry.first == key;
                    }),
                entries.end());
        } else if (type == 4) {
            int expected_count = 0;
            long long expected_prod = 0;
            for (const auto& entry : entries) {
                if (entry.first == key) {
                    ++expected_count;
                    expected_prod += entry.second;
                }
            }
            assert(trie.count(key) == expected_count);
            assert(trie.prod(key) == expected_prod);
        } else {
            const std::uint32_t upper = std::uint32_t(seed >> 20) & 1023U;
            const std::uint32_t target = std::uint32_t(seed >> 12) & 1023U;
            const std::uint32_t other = std::uint32_t(seed >> 4) & 1023U;
            const std::uint32_t lower = std::min(upper, other);
            const std::uint32_t range_upper =
                std::max(upper, other) + 1;
            int expected_count = 0;
            long long expected_prod = 0;
            int expected_equal_count = 0;
            long long expected_equal_prod = 0;
            int expected_less_equal_count = 0;
            long long expected_less_equal_prod = 0;
            int expected_greater_count = 0;
            long long expected_greater_prod = 0;
            int expected_greater_equal_count = 0;
            long long expected_greater_equal_prod = 0;
            int expected_range_count = 0;
            long long expected_range_prod = 0;
            std::vector<std::uint32_t> xor_values;
            xor_values.reserve(entries.size());
            for (const auto& entry : entries) {
                const std::uint32_t xor_value = entry.first ^ key;
                xor_values.push_back(xor_value);
                if (xor_value == target) {
                    ++expected_equal_count;
                    expected_equal_prod += entry.second;
                }
                if (xor_value < upper) {
                    ++expected_count;
                    expected_prod += entry.second;
                }
                if (xor_value <= upper) {
                    ++expected_less_equal_count;
                    expected_less_equal_prod += entry.second;
                }
                if (xor_value > upper) {
                    ++expected_greater_count;
                    expected_greater_prod += entry.second;
                }
                if (xor_value >= upper) {
                    ++expected_greater_equal_count;
                    expected_greater_equal_prod += entry.second;
                }
                if (lower <= xor_value && xor_value < range_upper) {
                    ++expected_range_count;
                    expected_range_prod += entry.second;
                }
            }
            std::sort(xor_values.begin(), xor_values.end());

            assert(trie.count_xor_equal(key, target) ==
                   expected_equal_count);
            assert(trie.prod_xor_equal(key, target) ==
                   expected_equal_prod);
            assert(trie.count_xor_less(key, upper) == expected_count);
            assert(trie.count_less_xor(key, upper) == expected_count);
            assert(trie.prod_xor_less(key, upper) == expected_prod);
            assert(trie.count_xor_less_equal(key, upper) ==
                   expected_less_equal_count);
            assert(trie.prod_xor_less_equal(key, upper) ==
                   expected_less_equal_prod);
            assert(trie.count_xor_greater(key, upper) ==
                   expected_greater_count);
            assert(trie.prod_xor_greater(key, upper) ==
                   expected_greater_prod);
            assert(trie.count_xor_greater_equal(key, upper) ==
                   expected_greater_equal_count);
            assert(trie.prod_xor_greater_equal(key, upper) ==
                   expected_greater_equal_prod);
            assert(trie.count_xor_range(key, lower, range_upper) ==
                   expected_range_count);
            assert(trie.prod_xor_range(key, lower, range_upper) ==
                   expected_range_prod);

            if (!xor_values.empty()) {
                const int k = int(seed % xor_values.size());
                assert(trie.kth_xor(k, key) == xor_values[k]);
                assert(trie.min_xor(key) == xor_values.front());
                assert(trie.max_xor(key) == xor_values.back());
            }
        }

        assert(trie.size() == int(entries.size()));
        long long expected_all_prod = 0;
        for (const auto& entry : entries) {
            expected_all_prod += entry.second;
        }
        assert(trie.all_prod() == expected_all_prod);
    }
}

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

    basic_test();
    randomized_test();

    using Sum = m1une::monoid::Add<int>;
    m1une::ds::BinaryTrieMonoid<Sum, std::uint32_t, 30> trie;

    int q;
    fast_input >> q;
    while (q--) {
        int type;
        std::uint32_t value;
        fast_input >> type >> value;
        if (type == 0) {
            if (!trie.contains(value)) trie.insert(value, 0);
        } else if (type == 1) {
            trie.erase_all(value);
        } else {
            fast_output << trie.min_xor(value) << '\n';
        }
    }
}
Back to top page