m1une's library

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

View on GitHub

:heavy_check_mark: verify/ds/range_query/range_sort_range_composite.test.cpp

Depends on

Code

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

#include "../../../ds/range_query/range_sort_range_composite.hpp"

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

#include "../../../math/modint.hpp"

namespace {

using Mint = m1une::math::modint998244353;
using Function = std::pair<Mint, Mint>;

struct AffineComposition {
    using value_type = Function;

    static value_type id() {
        return {Mint(1), Mint(0)};
    }

    static value_type op(const value_type& left, const value_type& right) {
        return {
            right.first * left.first,
            right.first * left.second + right.second
        };
    }
};

struct Item {
    int key;
    Function function;
};

Function naive_product(const std::vector<Item>& items, int left, int right) {
    Function result = AffineComposition::id();
    for (int i = left; i < right; i++) {
        result = AffineComposition::op(result, items[i].function);
    }
    return result;
}

void test_randomized() {
    using Data = m1une::ds::RangeSortRangeComposite<AffineComposition>;
    Data empty;
    assert(empty.empty());
    assert(empty.size() == 0);
    assert(empty.key_count() == 0);
    assert(empty.all_prod() == AffineComposition::id());

    std::uint64_t state = 818181;
    auto random = [&state]() {
        state ^= state << 7;
        state ^= state >> 9;
        return state;
    };

    for (int trial = 0; trial < 600; trial++) {
        int size = 1 + int(random() % 18);
        int key_count = 32;
        std::vector<int> available(key_count);
        for (int i = 0; i < key_count; i++) available[i] = i;
        for (int i = key_count - 1; i > 0; i--) {
            std::swap(available[i], available[random() % (i + 1)]);
        }

        std::vector<int> keys;
        std::vector<Function> functions;
        std::vector<Item> items;
        for (int i = 0; i < size; i++) {
            Function function = {
                Mint(1 + random() % 20),
                Mint(random() % 20)
            };
            keys.push_back(available[i]);
            functions.push_back(function);
            items.push_back(Item{available[i], function});
        }

        Data data(key_count, keys, functions);
        assert(data.size() == size);
        assert(!data.empty());
        assert(data.key_count() == key_count);

        for (int operation = 0; operation < 300; operation++) {
            int type = int(random() % 6);
            int left = int(random() % (size + 1));
            int right = int(random() % (size + 1));
            if (left > right) std::swap(left, right);
            if (type == 0) {
                int position = int(random() % size);
                std::vector<bool> used(key_count, false);
                for (const auto& item : items) used[item.key] = true;
                int key = items[position].key;
                if ((random() & 1U) != 0) {
                    do {
                        key = int(random() % key_count);
                    } while (used[key]);
                }
                Function function = {
                    Mint(1 + random() % 20),
                    Mint(random() % 20)
                };
                data.set(position, key, function);
                items[position] = Item{key, function};
            } else if (type == 1) {
                assert(data.prod(left, right) == naive_product(items, left, right));
            } else if (type == 2) {
                data.sort_ascending(left, right);
                std::sort(items.begin() + left, items.begin() + right, [](const Item& a, const Item& b) {
                    return a.key < b.key;
                });
            } else if (type == 3) {
                data.sort_descending(left, right);
                std::sort(items.begin() + left, items.begin() + right, [](const Item& a, const Item& b) {
                    return a.key > b.key;
                });
            } else if (type == 4) {
                int position = int(random() % size);
                auto [key, function] = data.get(position);
                assert(key == items[position].key);
                assert(function == items[position].function);
            } else {
                assert(data.all_prod() == naive_product(items, 0, size));
            }
        }
    }
}

struct Query {
    int type;
    int first;
    int second;
    int third;
    int fourth;
};

}  // namespace

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

    test_randomized();
    int n, q;
    fast_input >> n >> q;
    std::vector<int> keys(n);
    std::vector<Function> functions(n);
    std::vector<int> all_keys;
    all_keys.reserve(n + q);
    for (int i = 0; i < n; i++) {
        int a, b;
        fast_input >> keys[i] >> a >> b;
        functions[i] = {Mint(a), Mint(b)};
        all_keys.push_back(keys[i]);
    }

    std::vector<Query> queries(q);
    for (auto& query : queries) {
        fast_input >> query.type;
        if (query.type == 0) {
            fast_input >> query.first >> query.second >> query.third >> query.fourth;
            all_keys.push_back(query.second);
        } else if (query.type == 1) {
            fast_input >> query.first >> query.second >> query.third;
            query.fourth = 0;
        } else {
            fast_input >> query.first >> query.second;
            query.third = query.fourth = 0;
        }
    }

    std::sort(all_keys.begin(), all_keys.end());
    all_keys.erase(std::unique(all_keys.begin(), all_keys.end()), all_keys.end());
    for (int& key : keys) {
        key = int(std::lower_bound(all_keys.begin(), all_keys.end(), key) - all_keys.begin());
    }

    using Data = m1une::ds::RangeSortRangeComposite<AffineComposition>;
    Data data(int(all_keys.size()), keys, functions);
    for (const auto& query : queries) {
        if (query.type == 0) {
            int key = int(
                std::lower_bound(all_keys.begin(), all_keys.end(), query.second) - all_keys.begin()
            );
            data.set(query.first, key, Function{Mint(query.third), Mint(query.fourth)});
        } else if (query.type == 1) {
            Function function = data.prod(query.first, query.second);
            Mint answer = function.first * Mint(query.third) + function.second;
            fast_output << answer << '\n';
        } else if (query.type == 2) {
            data.sort_ascending(query.first, query.second);
        } else {
            data.sort_descending(query.first, query.second);
        }
    }
}
#line 1 "verify/ds/range_query/range_sort_range_composite.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/point_set_range_sort_range_composite"

#line 1 "ds/range_query/range_sort_range_composite.hpp"



#include <algorithm>
#include <bit>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#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 1 "ds/segtree/segtree.hpp"



#line 8 "ds/segtree/segtree.hpp"

#line 1 "math/bit_ceil.hpp"



namespace m1une {
namespace math {

template <typename T>
constexpr T bit_ceil(T n) {
    if (n <= 1) return 1;
    T x = 1;
    while (x < n) x <<= 1;
    return x;
}

}  // namespace math
}  // namespace m1une


#line 11 "ds/segtree/segtree.hpp"

namespace m1une {
namespace ds {

// A generic Segment Tree utilizing C++20 Concepts for type safety.
// It requires a Monoid struct that satisfies `m1une::monoid::IsMonoid`.
template <m1une::monoid::IsMonoid Monoid>
struct Segtree {
    using T = typename Monoid::value_type;

   private:
    int _n, _size, _log;
    std::vector<T> _d;

    void update(int k) {
        _d[k] = Monoid::op(_d[2 * k], _d[2 * k + 1]);
    }

   public:
    // Constructs an empty segment tree.
    Segtree() : Segtree(0) {}

    // Constructs a segment tree of size `n`, initialized with the identity element.
    explicit Segtree(int n) : Segtree(std::vector<T>(n, Monoid::id())) {}

    // Constructs a segment tree from an existing vector.
    explicit Segtree(const std::vector<T>& v) : _n(int(v.size())) {
        _size = m1une::math::bit_ceil((unsigned int)(_n));
        _log = 0;
        while ((1U << _log) < (unsigned int)(_size)) _log++;
        _d.assign(2 * _size, Monoid::id());
        for (int i = 0; i < _n; i++) _d[_size + i] = v[i];
        for (int i = _size - 1; i >= 1; i--) update(i);
    }
    explicit Segtree(std::vector<T>&& v) : _n(int(v.size())) {
        _size = m1une::math::bit_ceil((unsigned int)(_n));
        _log = 0;
        while ((1U << _log) < (unsigned int)(_size)) _log++;
        _d.assign(2 * _size, Monoid::id());
        for (int i = 0; i < _n; i++) _d[_size + i] = std::move(v[i]);
        for (int i = _size - 1; i >= 1; i--) update(i);
    }

    // Constructs a segment tree from a vector of a different type U.
    // It automatically adapts to the Monoid's initialization requirements:
    // 1. Monoid::make(val) if it exists.
    // 2. Monoid::make(val, index) if the monoid requires global indices.
    // 3. static_cast<T>(val) as a fallback for simple monoids.
    template <typename U>
    requires (!std::same_as<U, T>) && (
        requires(U x) { Monoid::make(x); } ||
        requires(U x, int i) { Monoid::make(x, i); } ||
        std::convertible_to<U, T>
    )
    explicit Segtree(const std::vector<U>& v) : _n(int(v.size())) {
        _size = m1une::math::bit_ceil((unsigned int)(_n));
        _log = 0;
        while ((1U << _log) < (unsigned int)(_size)) _log++;
        _d.assign(2 * _size, Monoid::id());
        for (int i = 0; i < _n; i++) {
            if constexpr (requires(U x) { Monoid::make(x); }) {
                _d[_size + i] = Monoid::make(v[i]);
            } else if constexpr (requires(U x, int idx) { Monoid::make(x, idx); }) {
                _d[_size + i] = Monoid::make(v[i], i);
            } else {
                _d[_size + i] = static_cast<T>(v[i]);
            }
        }
        for (int i = _size - 1; i >= 1; i--) update(i);
    }

    // Returns the number of elements.
    int size() const {
        return _n;
    }

    // Returns whether the tree is empty.
    bool empty() const {
        return _n == 0;
    }

    // Sets the value of the element at index `p` to `x`.
    void set(int p, T x) {
        assert(0 <= p && p < _n);
        p += _size;
        _d[p] = x;
        for (int i = 1; i <= _log; i++) update(p >> i);
    }

    // Returns the value of the element at index `p`.
    T get(int p) const {
        assert(0 <= p && p < _n);
        return _d[p + _size];
    }

    // Returns the value of the element at index `p`.
    T operator[](int p) const {
        return get(p);
    }

    // Returns the product (result of the monoid operation) in the range [l, r).
    T prod(int l, int r) const {
        assert(0 <= l && l <= r && r <= _n);
        T sml = Monoid::id(), smr = Monoid::id();
        l += _size;
        r += _size;
        while (l < r) {
            if (l & 1) sml = Monoid::op(sml, _d[l++]);
            if (r & 1) smr = Monoid::op(_d[--r], smr);
            l >>= 1;
            r >>= 1;
        }
        return Monoid::op(sml, smr);
    }

    // Returns the product of the entire array.
    T all_prod() const {
        return _d[1];
    }

    // Returns all elements as a vector.
    std::vector<T> to_vector() const {
        return to_vector(0, _n);
    }

    // Returns the elements in the range [l, r) as a vector.
    std::vector<T> to_vector(int l, int r) const {
        assert(0 <= l && l <= r && r <= _n);
        std::vector<T> res;
        res.reserve(r - l);
        for (int i = l; i < r; i++) res.push_back(_d[_size + i]);
        return res;
    }

    // Finds the largest `r` such that `f(prod(l, r))` is true.
    // Uses a custom functor or lambda `f`.
    template <class F>
    int max_right(int l, F f) const {
        assert(0 <= l && l <= _n);
        assert(f(Monoid::id()));
        if (l == _n) return _n;
        l += _size;
        T sm = Monoid::id();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!f(Monoid::op(sm, _d[l]))) {
                while (l < _size) {
                    l = (2 * l);
                    if (f(Monoid::op(sm, _d[l]))) {
                        sm = Monoid::op(sm, _d[l]);
                        l++;
                    }
                }
                return l - _size;
            }
            sm = Monoid::op(sm, _d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    // Finds the smallest `l` such that `f(prod(l, r))` is true.
    template <class F>
    int min_left(int r, F f) const {
        assert(0 <= r && r <= _n);
        assert(f(Monoid::id()));
        if (r == 0) return 0;
        r += _size;
        T sm = Monoid::id();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!f(Monoid::op(_d[r], sm))) {
                while (r < _size) {
                    r = (2 * r + 1);
                    if (f(Monoid::op(_d[r], sm))) {
                        sm = Monoid::op(_d[r], sm);
                        r--;
                    }
                }
                return r + 1 - _size;
            }
            sm = Monoid::op(_d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }
};

}  // namespace ds
}  // namespace m1une


#line 15 "ds/range_query/range_sort_range_composite.hpp"

namespace m1une {
namespace ds {

namespace detail {

class RangeSortBoundarySet {
   private:
    static constexpr int word_bits = 64;

    int _n;
    std::vector<std::vector<std::uint64_t>> _levels;

   public:
    explicit RangeSortBoundarySet(int n = 0) : _n(n) {
        assert(n >= 0);
        int size = std::max(n, 1);
        do {
            int words = (size + word_bits - 1) / word_bits;
            _levels.emplace_back(words, 0);
            size = words;
        } while (size > 1);
    }

    bool contains(int index) const {
        assert(0 <= index && index < _n);
        return ((_levels[0][index / word_bits] >> (index % word_bits)) & 1U) != 0;
    }

    void insert(int index) {
        assert(0 <= index && index < _n);
        for (auto& level : _levels) {
            level[index / word_bits] |= std::uint64_t(1) << (index % word_bits);
            index /= word_bits;
        }
    }

    void erase(int index) {
        assert(0 <= index && index < _n);
        for (auto& level : _levels) {
            level[index / word_bits] &= ~(std::uint64_t(1) << (index % word_bits));
            if (level[index / word_bits] != 0) break;
            index /= word_bits;
        }
    }

    int next(int index) const {
        if (index < 0) index = 0;
        for (int level = 0; level < int(_levels.size()); level++) {
            if (index / word_bits >= int(_levels[level].size())) break;
            std::uint64_t word = _levels[level][index / word_bits] >> (index % word_bits);
            if (word == 0) {
                index = index / word_bits + 1;
                continue;
            }
            index += int(std::countr_zero(word));
            for (int lower = level - 1; lower >= 0; lower--) {
                index *= word_bits;
                std::uint64_t lower_word = _levels[lower][index / word_bits];
                index += int(std::countr_zero(lower_word));
            }
            return std::min(index, _n);
        }
        return _n;
    }

    int previous(int index) const {
        if (_n == 0 || index < 0) return -1;
        if (index >= _n) index = _n - 1;
        for (int level = 0; level < int(_levels.size()); level++) {
            std::uint64_t word = _levels[level][index / word_bits]
                               << (word_bits - 1 - index % word_bits);
            if (word == 0) {
                index = index / word_bits - 1;
                if (index < 0) break;
                continue;
            }
            index += 63 - int(std::countl_zero(word)) - (word_bits - 1);
            for (int lower = level - 1; lower >= 0; lower--) {
                index *= word_bits;
                std::uint64_t lower_word = _levels[lower][index / word_bits];
                index += 63 - int(std::countl_zero(lower_word));
            }
            return index;
        }
        return -1;
    }
};

}  // namespace detail

// Maintains a sequence under point assignment, range product, and range sorting
// by distinct compressed integer keys.
template <m1une::monoid::IsMonoid Monoid>
class RangeSortRangeComposite {
   public:
    using T = typename Monoid::value_type;

   private:
    struct Node {
        T product;
        T reverse_product;
        int count;
        int left;
        int right;

        Node(T value, int node_count)
            : product(std::move(value)),
              reverse_product(product),
              count(node_count),
              left(0),
              right(0) {}
    };

    int _n;
    int _key_count;
    int _key_height;
    detail::RangeSortBoundarySet _boundaries;
    Segtree<Monoid> _segments;
    std::vector<bool> _reversed;
    std::vector<int> _roots;
    std::vector<int> _key_frequency;
    std::vector<Node> _nodes;
    int _node_count;
    std::size_t _node_limit;

    static int key_height(int key_count) {
        int result = 0;
        while (key_count > 1) {
            key_count = (key_count + 1) / 2;
            result++;
        }
        return result;
    }

    void reset_node_pool() {
        T identity = Monoid::id();
        if (_nodes.empty()) {
            _nodes.emplace_back(std::move(identity), 0);
        } else {
            _nodes[0] = Node(std::move(identity), 0);
        }
        _node_count = 1;
    }

    int new_node(T value = Monoid::id()) {
        int result = _node_count++;
        if (result == int(_nodes.size())) {
            _nodes.emplace_back(std::move(value), 1);
        } else {
            _nodes[result] = Node(std::move(value), 1);
        }
        return result;
    }

    void update(int node) {
        int left = _nodes[node].left;
        int right = _nodes[node].right;
        if (left == 0 && right == 0) return;
        if (left == 0) {
            _nodes[node].product = _nodes[right].product;
            _nodes[node].reverse_product = _nodes[right].reverse_product;
            _nodes[node].count = _nodes[right].count;
            return;
        }
        if (right == 0) {
            _nodes[node].product = _nodes[left].product;
            _nodes[node].reverse_product = _nodes[left].reverse_product;
            _nodes[node].count = _nodes[left].count;
            return;
        }
        _nodes[node].product = Monoid::op(_nodes[left].product, _nodes[right].product);
        _nodes[node].reverse_product = Monoid::op(
            _nodes[right].reverse_product,
            _nodes[left].reverse_product
        );
        _nodes[node].count = _nodes[left].count + _nodes[right].count;
    }

    void set_key(int node, int left, int right, int key, const T& value) {
        if (right - left == 1) {
            _nodes[node].product = value;
            _nodes[node].reverse_product = value;
            return;
        }
        int middle = (left + right) / 2;
        if (key < middle) {
            if (_nodes[node].left == 0) _nodes[node].left = new_node();
            int child = _nodes[node].left;
            set_key(child, left, middle, key, value);
        } else {
            if (_nodes[node].right == 0) _nodes[node].right = new_node();
            int child = _nodes[node].right;
            set_key(child, middle, right, key, value);
        }
        update(node);
    }

    std::pair<int, int> split_tree(int node, int count) {
        if (count == 0) return {0, node};
        if (count == _nodes[node].count) return {node, 0};

        int second = new_node();
        int left_count = _nodes[_nodes[node].left].count;
        if (count <= left_count) {
            auto [first_left, second_left] = split_tree(_nodes[node].left, count);
            int old_right = _nodes[node].right;
            _nodes[node].left = first_left;
            _nodes[node].right = 0;
            _nodes[second].left = second_left;
            _nodes[second].right = old_right;
        } else {
            auto [first_right, second_right]
                = split_tree(_nodes[node].right, count - left_count);
            _nodes[node].right = first_right;
            _nodes[second].left = 0;
            _nodes[second].right = second_right;
        }
        update(node);
        update(second);
        return {node, second};
    }

    int merge_trees(int first, int second) {
        if (first == 0 || second == 0) return first != 0 ? first : second;
        int first_left = _nodes[first].left;
        int first_right = _nodes[first].right;
        _nodes[first].left = merge_trees(first_left, _nodes[second].left);
        _nodes[first].right = merge_trees(first_right, _nodes[second].right);
        update(first);
        return first;
    }

    int only_key(int node, int left, int right) const {
        assert(node != 0 && _nodes[node].count == 1);
        while (right - left > 1) {
            int middle = (left + right) / 2;
            if (_nodes[node].left != 0) {
                node = _nodes[node].left;
                right = middle;
            } else {
                node = _nodes[node].right;
                left = middle;
            }
        }
        return left;
    }

    void split_at(int position) {
        if (position == _n || _boundaries.contains(position)) return;
        int first = _boundaries.previous(position);
        int next = _boundaries.next(first + 1);
        assert(first >= 0 && next > position);
        _boundaries.insert(position);

        if (!_reversed[first]) {
            auto [left, right] = split_tree(_roots[first], position - first);
            _roots[first] = left;
            _roots[position] = right;
            _reversed[first] = false;
            _reversed[position] = false;
            _segments.set(first, _nodes[left].product);
            _segments.set(position, _nodes[right].product);
        } else {
            auto [left, right] = split_tree(_roots[first], next - position);
            _roots[first] = right;
            _roots[position] = left;
            _reversed[first] = true;
            _reversed[position] = true;
            _segments.set(first, _nodes[right].reverse_product);
            _segments.set(position, _nodes[left].reverse_product);
        }
    }

    void dump_tree(
        int node,
        int left,
        int right,
        bool reversed,
        std::vector<int>& keys,
        std::vector<T>& values
    ) const {
        if (node == 0) return;
        if (right - left == 1) {
            assert(_nodes[node].count == 1);
            keys.push_back(left);
            values.push_back(_nodes[node].product);
            return;
        }
        int middle = (left + right) / 2;
        if (!reversed) {
            dump_tree(_nodes[node].left, left, middle, false, keys, values);
            dump_tree(_nodes[node].right, middle, right, false, keys, values);
        } else {
            dump_tree(_nodes[node].right, middle, right, true, keys, values);
            dump_tree(_nodes[node].left, left, middle, true, keys, values);
        }
    }

    void initialize_runs(const std::vector<int>& keys, const std::vector<T>& values) {
        reset_node_pool();
        _boundaries = detail::RangeSortBoundarySet(_n);
        _segments = Segtree<Monoid>(values);
        _reversed.assign(_n, false);
        _roots.assign(_n, 0);
        for (int index = 0; index < _n; index++) {
            _boundaries.insert(index);
            _roots[index] = new_node();
            set_key(_roots[index], 0, _key_count, keys[index], values[index]);
        }
    }

    void rebuild() {
        std::vector<int> keys;
        std::vector<T> values;
        keys.reserve(_n);
        values.reserve(_n);
        for (int position = _boundaries.next(0); position < _n;
             position = _boundaries.next(position + 1)) {
            dump_tree(
                _roots[position],
                0,
                _key_count,
                _reversed[position],
                keys,
                values
            );
        }
        assert(int(keys.size()) == _n);
        initialize_runs(keys, values);
    }

    void ensure_node_space() {
        std::size_t margin = std::size_t(4) * std::size_t(_key_height + 2);
        if (std::size_t(_node_count) + margin > _node_limit) rebuild();
    }

   public:
    RangeSortRangeComposite()
        : _n(0),
          _key_count(0),
          _key_height(0),
          _boundaries(0),
          _segments(),
          _node_count(0),
          _node_limit(1) {
        reset_node_pool();
    }

    RangeSortRangeComposite(
        int key_count,
        const std::vector<int>& keys,
        const std::vector<T>& values
    )
        : _n(0),
          _key_count(key_count),
          _key_height(0),
          _boundaries(0),
          _segments(),
          _node_count(0),
          _node_limit(1) {
        assert(key_count >= 0);
        assert(keys.size() == values.size());
        assert(keys.size() <= std::size_t(std::numeric_limits<int>::max()));
        _n = int(keys.size());
        assert(_n == 0 || key_count > 0);
        _key_height = key_height(key_count);
        _key_frequency.assign(key_count, 0);
        for (int key : keys) {
            assert(0 <= key && key < key_count);
            assert(_key_frequency[key] == 0);
            _key_frequency[key] = 1;
        }

        std::size_t height = std::size_t(_key_height + 1);
        std::size_t initial_nodes = std::size_t(_n) * height + 1;
        std::size_t slack = std::max<std::size_t>(1024, std::size_t(8) * std::size_t(_n) + 64);
        _node_limit = initial_nodes + slack;
        _nodes.reserve(_node_limit);
        initialize_runs(keys, values);
        assert(std::size_t(_node_count) <= initial_nodes);
    }

    int size() const {
        return _n;
    }

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

    int key_count() const {
        return _key_count;
    }

    std::pair<int, T> get(int position) {
        assert(0 <= position && position < _n);
        ensure_node_space();
        split_at(position);
        split_at(position + 1);
        int key = only_key(_roots[position], 0, _key_count);
        return {key, _nodes[_roots[position]].product};
    }

    void set(int position, int key, T value) {
        assert(0 <= position && position < _n);
        assert(0 <= key && key < _key_count);
        ensure_node_space();
        split_at(position);
        split_at(position + 1);
        int old_key = only_key(_roots[position], 0, _key_count);
        assert(key == old_key || _key_frequency[key] == 0);
        _key_frequency[old_key]--;
        _key_frequency[key]++;

        _reversed[position] = false;
        _roots[position] = new_node();
        set_key(_roots[position], 0, _key_count, key, value);
        _segments.set(position, value);
    }

    T prod(int left, int right) {
        assert(0 <= left && left <= right && right <= _n);
        if (left == right) return Monoid::id();
        ensure_node_space();
        split_at(left);
        split_at(right);
        return _segments.prod(left, right);
    }

    T all_prod() const {
        return _segments.all_prod();
    }

    void sort_ascending(int left, int right) {
        assert(0 <= left && left <= right && right <= _n);
        if (left == right) return;
        ensure_node_space();
        split_at(left);
        split_at(right);
        while (true) {
            int next = _boundaries.next(left + 1);
            if (next == right) break;
            _roots[left] = merge_trees(_roots[left], _roots[next]);
            _roots[next] = 0;
            _reversed[next] = false;
            _boundaries.erase(next);
            _segments.set(next, Monoid::id());
        }
        _reversed[left] = false;
        _segments.set(left, _nodes[_roots[left]].product);
    }

    void sort_descending(int left, int right) {
        assert(0 <= left && left <= right && right <= _n);
        if (left == right) return;
        sort_ascending(left, right);
        _reversed[left] = true;
        _segments.set(left, _nodes[_roots[left]].reverse_product);
    }
};

}  // namespace ds
}  // namespace m1une


#line 4 "verify/ds/range_query/range_sort_range_composite.test.cpp"

#line 1 "utilities/fast_io.hpp"



#line 5 "utilities/fast_io.hpp"
#include <array>
#include <cerrno>
#include <charconv>
#line 9 "utilities/fast_io.hpp"
#include <cstdio>
#include <cstdlib>
#line 12 "utilities/fast_io.hpp"
#include <cstring>
#include <iterator>
#include <string>
#include <sys/stat.h>
#include <type_traits>
#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 9 "verify/ds/range_query/range_sort_range_composite.test.cpp"
#include <tuple>
#line 12 "verify/ds/range_query/range_sort_range_composite.test.cpp"

#line 1 "math/modint.hpp"



#line 6 "math/modint.hpp"
#include <iostream>
#line 9 "math/modint.hpp"

namespace m1une {
namespace math {

template <uint32_t Modulus>
struct ModInt {
    static_assert(0 < Modulus, "Modulus must be positive");

   private:
    uint32_t _v;

   public:
    static constexpr uint32_t mod() {
        return Modulus;
    }

    static constexpr ModInt raw(uint32_t v) noexcept {
        ModInt x;
        x._v = v;
        return x;
    }

    constexpr ModInt() noexcept : _v(0) {}

    template <class Integer, std::enable_if_t<std::is_integral_v<Integer>, int> = 0>
    constexpr ModInt(Integer v) noexcept {
        if constexpr (std::is_signed_v<Integer>) {
            int64_t x = static_cast<int64_t>(v) % static_cast<int64_t>(Modulus);
            if (x < 0) x += Modulus;
            _v = static_cast<uint32_t>(x);
        } else {
            _v = static_cast<uint32_t>(static_cast<uint64_t>(v) % Modulus);
        }
    }

    constexpr uint32_t val() const noexcept {
        return _v;
    }

    constexpr ModInt& operator++() noexcept {
        _v++;
        if (_v == Modulus) _v = 0;
        return *this;
    }

    constexpr ModInt& operator--() noexcept {
        if (_v == 0) _v = Modulus;
        _v--;
        return *this;
    }

    constexpr ModInt operator++(int) noexcept {
        ModInt res = *this;
        ++*this;
        return res;
    }

    constexpr ModInt operator--(int) noexcept {
        ModInt res = *this;
        --*this;
        return res;
    }

    constexpr ModInt& operator+=(const ModInt& rhs) noexcept {
        _v += rhs._v;
        if (_v >= Modulus) _v -= Modulus;
        return *this;
    }

    constexpr ModInt& operator-=(const ModInt& rhs) noexcept {
        _v -= rhs._v;
        if (_v >= Modulus) _v += Modulus;
        return *this;
    }

    constexpr ModInt& operator*=(const ModInt& rhs) noexcept {
        uint64_t z = _v;
        z *= rhs._v;
        _v = static_cast<uint32_t>(z % Modulus);
        return *this;
    }

    constexpr ModInt& operator/=(const ModInt& rhs) noexcept {
        return *this *= rhs.inv();
    }

    constexpr ModInt operator+(const ModInt& rhs) const noexcept {
        return ModInt(*this) += rhs;
    }
    constexpr ModInt operator-(const ModInt& rhs) const noexcept {
        return ModInt(*this) -= rhs;
    }
    constexpr ModInt operator*(const ModInt& rhs) const noexcept {
        return ModInt(*this) *= rhs;
    }
    constexpr ModInt operator/(const ModInt& rhs) const noexcept {
        return ModInt(*this) /= rhs;
    }

    constexpr bool operator==(const ModInt& rhs) const noexcept {
        return _v == rhs._v;
    }
    constexpr bool operator!=(const ModInt& rhs) const noexcept {
        return _v != rhs._v;
    }

    constexpr ModInt pow(long long n) const noexcept {
        ModInt res = raw(1 % Modulus);
        ModInt x = n < 0 ? inv() : *this;
        uint64_t exponent = n < 0 ? uint64_t(-(n + 1)) + 1 : uint64_t(n);
        while (exponent > 0) {
            if (exponent & 1) res *= x;
            x *= x;
            exponent >>= 1;
        }
        return res;
    }

    constexpr ModInt inv() const noexcept {
        int64_t a = _v, b = Modulus, u = 1, v = 0;
        while (b) {
            int64_t t = a / b;
            a -= t * b;
            std::swap(a, b);
            u -= t * v;
            std::swap(u, v);
        }
        assert(a == 1);
        u %= Modulus;
        if (u < 0) u += Modulus;
        return raw(static_cast<uint32_t>(u));
    }

    friend std::ostream& operator<<(std::ostream& os, const ModInt& rhs) {
        return os << rhs._v;
    }

    friend std::istream& operator>>(std::istream& is, ModInt& rhs) {
        long long v;
        is >> v;
        rhs = ModInt(v);
        return is;
    }
};

using modint998244353 = ModInt<998244353>;
using modint1000000007 = ModInt<1000000007>;

template <int Id = 0>
struct DynamicModInt {
   private:
    uint32_t _v;
    inline static uint32_t _mod = 1;

   public:
    static uint32_t mod() noexcept {
        return _mod;
    }

    static void set_mod(uint32_t modulus) noexcept {
        assert(modulus > 0);
        assert(modulus <= uint32_t(1) << 31);
        _mod = modulus;
    }

    static DynamicModInt raw(uint32_t v) noexcept {
        assert(v < _mod);
        DynamicModInt x;
        x._v = v;
        return x;
    }

    DynamicModInt() noexcept : _v(0) {}

    template <class Integer, std::enable_if_t<std::is_integral_v<Integer>, int> = 0>
    DynamicModInt(Integer v) noexcept {
        if constexpr (std::is_signed_v<Integer>) {
            int64_t x = static_cast<int64_t>(v) % static_cast<int64_t>(_mod);
            if (x < 0) x += _mod;
            _v = static_cast<uint32_t>(x);
        } else {
            _v = static_cast<uint32_t>(static_cast<uint64_t>(v) % _mod);
        }
    }

    uint32_t val() const noexcept {
        return _v;
    }

    DynamicModInt& operator++() noexcept {
        _v++;
        if (_v == _mod) _v = 0;
        return *this;
    }

    DynamicModInt& operator--() noexcept {
        if (_v == 0) _v = _mod;
        _v--;
        return *this;
    }

    DynamicModInt operator++(int) noexcept {
        DynamicModInt result = *this;
        ++*this;
        return result;
    }

    DynamicModInt operator--(int) noexcept {
        DynamicModInt result = *this;
        --*this;
        return result;
    }

    DynamicModInt& operator+=(const DynamicModInt& rhs) noexcept {
        _v += rhs._v;
        if (_v >= _mod) _v -= _mod;
        return *this;
    }

    DynamicModInt& operator-=(const DynamicModInt& rhs) noexcept {
        _v -= rhs._v;
        if (_v >= _mod) _v += _mod;
        return *this;
    }

    DynamicModInt& operator*=(const DynamicModInt& rhs) noexcept {
        _v = static_cast<uint32_t>(uint64_t(_v) * rhs._v % _mod);
        return *this;
    }

    DynamicModInt& operator/=(const DynamicModInt& rhs) noexcept {
        return *this *= rhs.inv();
    }

    DynamicModInt operator+(const DynamicModInt& rhs) const noexcept {
        return DynamicModInt(*this) += rhs;
    }

    DynamicModInt operator-(const DynamicModInt& rhs) const noexcept {
        return DynamicModInt(*this) -= rhs;
    }

    DynamicModInt operator*(const DynamicModInt& rhs) const noexcept {
        return DynamicModInt(*this) *= rhs;
    }

    DynamicModInt operator/(const DynamicModInt& rhs) const noexcept {
        return DynamicModInt(*this) /= rhs;
    }

    bool operator==(const DynamicModInt& rhs) const noexcept {
        return _v == rhs._v;
    }

    bool operator!=(const DynamicModInt& rhs) const noexcept {
        return _v != rhs._v;
    }

    DynamicModInt pow(long long exponent) const noexcept {
        DynamicModInt result = raw(1 % _mod);
        DynamicModInt base = exponent < 0 ? inv() : *this;
        uint64_t magnitude =
            exponent < 0 ? uint64_t(-(exponent + 1)) + 1 : uint64_t(exponent);
        while (magnitude > 0) {
            if (magnitude & 1) result *= base;
            base *= base;
            magnitude >>= 1;
        }
        return result;
    }

    DynamicModInt inv() const noexcept {
        int64_t a = _v, b = _mod, u = 1, v = 0;
        while (b) {
            int64_t quotient = a / b;
            a -= quotient * b;
            std::swap(a, b);
            u -= quotient * v;
            std::swap(u, v);
        }
        assert(a == 1);
        u %= _mod;
        if (u < 0) u += _mod;
        return raw(static_cast<uint32_t>(u));
    }

    friend std::ostream& operator<<(std::ostream& os, const DynamicModInt& rhs) {
        return os << rhs._v;
    }

    friend std::istream& operator>>(std::istream& is, DynamicModInt& rhs) {
        long long value;
        is >> value;
        rhs = DynamicModInt(value);
        return is;
    }
};

}  // namespace math
}  // namespace m1une


#line 14 "verify/ds/range_query/range_sort_range_composite.test.cpp"

namespace {

using Mint = m1une::math::modint998244353;
using Function = std::pair<Mint, Mint>;

struct AffineComposition {
    using value_type = Function;

    static value_type id() {
        return {Mint(1), Mint(0)};
    }

    static value_type op(const value_type& left, const value_type& right) {
        return {
            right.first * left.first,
            right.first * left.second + right.second
        };
    }
};

struct Item {
    int key;
    Function function;
};

Function naive_product(const std::vector<Item>& items, int left, int right) {
    Function result = AffineComposition::id();
    for (int i = left; i < right; i++) {
        result = AffineComposition::op(result, items[i].function);
    }
    return result;
}

void test_randomized() {
    using Data = m1une::ds::RangeSortRangeComposite<AffineComposition>;
    Data empty;
    assert(empty.empty());
    assert(empty.size() == 0);
    assert(empty.key_count() == 0);
    assert(empty.all_prod() == AffineComposition::id());

    std::uint64_t state = 818181;
    auto random = [&state]() {
        state ^= state << 7;
        state ^= state >> 9;
        return state;
    };

    for (int trial = 0; trial < 600; trial++) {
        int size = 1 + int(random() % 18);
        int key_count = 32;
        std::vector<int> available(key_count);
        for (int i = 0; i < key_count; i++) available[i] = i;
        for (int i = key_count - 1; i > 0; i--) {
            std::swap(available[i], available[random() % (i + 1)]);
        }

        std::vector<int> keys;
        std::vector<Function> functions;
        std::vector<Item> items;
        for (int i = 0; i < size; i++) {
            Function function = {
                Mint(1 + random() % 20),
                Mint(random() % 20)
            };
            keys.push_back(available[i]);
            functions.push_back(function);
            items.push_back(Item{available[i], function});
        }

        Data data(key_count, keys, functions);
        assert(data.size() == size);
        assert(!data.empty());
        assert(data.key_count() == key_count);

        for (int operation = 0; operation < 300; operation++) {
            int type = int(random() % 6);
            int left = int(random() % (size + 1));
            int right = int(random() % (size + 1));
            if (left > right) std::swap(left, right);
            if (type == 0) {
                int position = int(random() % size);
                std::vector<bool> used(key_count, false);
                for (const auto& item : items) used[item.key] = true;
                int key = items[position].key;
                if ((random() & 1U) != 0) {
                    do {
                        key = int(random() % key_count);
                    } while (used[key]);
                }
                Function function = {
                    Mint(1 + random() % 20),
                    Mint(random() % 20)
                };
                data.set(position, key, function);
                items[position] = Item{key, function};
            } else if (type == 1) {
                assert(data.prod(left, right) == naive_product(items, left, right));
            } else if (type == 2) {
                data.sort_ascending(left, right);
                std::sort(items.begin() + left, items.begin() + right, [](const Item& a, const Item& b) {
                    return a.key < b.key;
                });
            } else if (type == 3) {
                data.sort_descending(left, right);
                std::sort(items.begin() + left, items.begin() + right, [](const Item& a, const Item& b) {
                    return a.key > b.key;
                });
            } else if (type == 4) {
                int position = int(random() % size);
                auto [key, function] = data.get(position);
                assert(key == items[position].key);
                assert(function == items[position].function);
            } else {
                assert(data.all_prod() == naive_product(items, 0, size));
            }
        }
    }
}

struct Query {
    int type;
    int first;
    int second;
    int third;
    int fourth;
};

}  // namespace

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

    test_randomized();
    int n, q;
    fast_input >> n >> q;
    std::vector<int> keys(n);
    std::vector<Function> functions(n);
    std::vector<int> all_keys;
    all_keys.reserve(n + q);
    for (int i = 0; i < n; i++) {
        int a, b;
        fast_input >> keys[i] >> a >> b;
        functions[i] = {Mint(a), Mint(b)};
        all_keys.push_back(keys[i]);
    }

    std::vector<Query> queries(q);
    for (auto& query : queries) {
        fast_input >> query.type;
        if (query.type == 0) {
            fast_input >> query.first >> query.second >> query.third >> query.fourth;
            all_keys.push_back(query.second);
        } else if (query.type == 1) {
            fast_input >> query.first >> query.second >> query.third;
            query.fourth = 0;
        } else {
            fast_input >> query.first >> query.second;
            query.third = query.fourth = 0;
        }
    }

    std::sort(all_keys.begin(), all_keys.end());
    all_keys.erase(std::unique(all_keys.begin(), all_keys.end()), all_keys.end());
    for (int& key : keys) {
        key = int(std::lower_bound(all_keys.begin(), all_keys.end(), key) - all_keys.begin());
    }

    using Data = m1une::ds::RangeSortRangeComposite<AffineComposition>;
    Data data(int(all_keys.size()), keys, functions);
    for (const auto& query : queries) {
        if (query.type == 0) {
            int key = int(
                std::lower_bound(all_keys.begin(), all_keys.end(), query.second) - all_keys.begin()
            );
            data.set(query.first, key, Function{Mint(query.third), Mint(query.fourth)});
        } else if (query.type == 1) {
            Function function = data.prod(query.first, query.second);
            Mint answer = function.first * Mint(query.third) + function.second;
            fast_output << answer << '\n';
        } else if (query.type == 2) {
            data.sort_ascending(query.first, query.second);
        } else {
            data.sort_descending(query.first, query.second);
        }
    }
}
Back to top page