m1une's library

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

View on GitHub

:heavy_check_mark: verify/ds/dynamic_connectivity/dynamic_connectivity.test.cpp

Depends on

Code

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

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

#include "../../../ds/dynamic_connectivity/all.hpp"

struct NaiveDynamicGraph {
    struct Edge {
        int u;
        int v;
        bool alive;
    };

    int n;
    std::vector<Edge> edges;

    explicit NaiveDynamicGraph(int n) : n(n) {}

    int add_edge(int u, int v) {
        int id = int(edges.size());
        edges.push_back(Edge{u, v, true});
        return id;
    }

    bool erase_edge(int id) {
        if (!edges[id].alive) return false;
        edges[id].alive = false;
        return true;
    }

    std::vector<int> component(int start) const {
        std::vector<std::vector<int>> graph(n);
        for (const Edge& edge : edges) {
            if (!edge.alive || edge.u == edge.v) continue;
            graph[edge.u].push_back(edge.v);
            graph[edge.v].push_back(edge.u);
        }
        std::vector<int> visited(n, false);
        std::queue<int> queue;
        std::vector<int> vertices;
        visited[start] = true;
        queue.push(start);
        while (!queue.empty()) {
            int v = queue.front();
            queue.pop();
            vertices.push_back(v);
            for (int to : graph[v]) {
                if (visited[to]) continue;
                visited[to] = true;
                queue.push(to);
            }
        }
        return vertices;
    }

    bool connected(int u, int v) const {
        std::vector<int> vertices = component(u);
        for (int x : vertices) {
            if (x == v) return true;
        }
        return false;
    }

    int component_count() const {
        std::vector<bool> visited(n, false);
        int result = 0;
        for (int v = 0; v < n; v++) {
            if (visited[v]) continue;
            result++;
            for (int x : component(v)) visited[x] = true;
        }
        return result;
    }
};

void test_online_basic() {
    m1une::ds::OnlineDynamicConnectivity graph(4);
    graph.reserve_edges(8);
    int e01 = graph.add_edge(0, 1);
    int e12 = graph.add_edge(1, 2);
    int e02 = graph.add_edge(0, 2);
    int loop = graph.add_edge(3, 3);
    assert(graph.connected(0, 2));
    assert(graph.component_size(0) == 3);
    assert(graph.component_count() == 2);
    assert(graph.active_edge_count() == 4);

    assert(graph.erase_edge(e12));
    assert(graph.connected(0, 2));
    assert(graph.erase_edge(e02));
    assert(!graph.connected(0, 2));
    assert(graph.component_count() == 3);
    assert(!graph.erase_edge(e02));
    assert(graph.erase_edge(loop));
    assert(graph.erase_edge(e01));
    assert(graph.component_count() == 4);
}

void test_offline_basic() {
    m1une::ds::OfflineDynamicConnectivity graph(3);
    graph.reserve_edges(8);
    graph.reserve_queries(8);
    int e01 = graph.add_edge(0, 1);
    int q0 = graph.add_query(0, 2);
    int e12 = graph.add_edge(1, 2);
    int q1 = graph.add_query(0, 2);
    assert(graph.erase_edge(e01));
    int q2 = graph.add_query(0, 2);
    assert(!graph.erase_edge(e01));
    int parallel = graph.add_edge(1, 2);
    int q3 = graph.add_query(1, 2);
    assert(graph.erase_edge(e12));
    int q4 = graph.add_query(1, 2);
    assert(graph.erase_edge(parallel));
    int q5 = graph.add_query(1, 2);

    std::vector<bool> answer = graph.solve();
    assert(!answer[q0]);
    assert(answer[q1]);
    assert(!answer[q2]);
    assert(answer[q3]);
    assert(answer[q4]);
    assert(!answer[q5]);
    assert(answer == graph.solve());

    int restored = graph.add_edge(0, 2);
    int q6 = graph.add_query(0, 2);
    answer = graph.solve();
    assert(answer[q6]);
    assert(graph.erase_edge(restored));
}

void test_online_random() {
    std::mt19937 random(123456789);
    for (int test = 0; test < 80; test++) {
        int n = 1 + random() % 15;
        m1une::ds::OnlineDynamicConnectivity graph(n);
        NaiveDynamicGraph naive(n);
        std::vector<int> active;
        for (int operation = 0; operation < 1000; operation++) {
            int type = random() % 5;
            if (type <= 1 || active.empty()) {
                int u = random() % n;
                int v = random() % n;
                int id = graph.add_edge(u, v);
                assert(id == naive.add_edge(u, v));
                active.push_back(id);
            } else if (type == 2) {
                int index = random() % active.size();
                int id = active[index];
                std::swap(active[index], active.back());
                active.pop_back();
                assert(graph.erase_edge(id));
                assert(naive.erase_edge(id));
            } else {
                int u = random() % n;
                int v = random() % n;
                assert(graph.connected(u, v) == naive.connected(u, v));
                assert(graph.component_size(u) == int(naive.component(u).size()));
            }
            assert(graph.active_edge_count() == int(active.size()));
            assert(graph.component_count() == naive.component_count());
        }
    }
}

void test_offline_random() {
    std::mt19937 random(987654321);
    for (int test = 0; test < 100; test++) {
        int n = 1 + random() % 12;
        m1une::ds::OfflineDynamicConnectivity graph(n);
        NaiveDynamicGraph naive(n);
        std::vector<int> active;
        std::vector<bool> expected;
        for (int operation = 0; operation < 500; operation++) {
            int type = random() % 4;
            if (type == 0 || active.empty()) {
                int u = random() % n;
                int v = random() % n;
                int id = graph.add_edge(u, v);
                assert(id == naive.add_edge(u, v));
                active.push_back(id);
            } else if (type == 1) {
                int index = random() % active.size();
                int id = active[index];
                std::swap(active[index], active.back());
                active.pop_back();
                assert(graph.erase_edge(id));
                assert(naive.erase_edge(id));
            } else {
                int u = random() % n;
                int v = random() % n;
                assert(graph.add_query(u, v) == int(expected.size()));
                expected.push_back(naive.connected(u, v));
            }
        }
        assert(graph.solve() == expected);
    }
}

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

    test_online_basic();
    test_offline_basic();
    test_online_random();
    test_offline_random();

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

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



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

namespace m1une {
namespace utilities {

struct FastOutput;

namespace internal {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}  // namespace internal

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}  // namespace utilities
}  // namespace m1une


#line 5 "verify/ds/dynamic_connectivity/dynamic_connectivity.test.cpp"
#include <queue>
#include <random>
#line 9 "verify/ds/dynamic_connectivity/dynamic_connectivity.test.cpp"

#line 1 "ds/dynamic_connectivity/all.hpp"



#line 1 "ds/dynamic_connectivity/offline_dynamic_connectivity.hpp"



#line 8 "ds/dynamic_connectivity/offline_dynamic_connectivity.hpp"

#line 1 "ds/dsu/rollback_dsu.hpp"



#line 7 "ds/dsu/rollback_dsu.hpp"

namespace m1une {
namespace ds {

struct RollbackDsu {
   private:
    struct HistoryEntry {
        int first;
        int first_value;
        int second;
        int second_value;
    };

    int _n;
    int _component_count;
    std::vector<int> parent_or_size;
    std::vector<HistoryEntry> history;

    static int check_size(int n) {
        assert(0 <= n);
        return n;
    }

   public:
    RollbackDsu() : RollbackDsu(0) {}

    explicit RollbackDsu(int n)
        : _n(check_size(n)), _component_count(_n), parent_or_size(_n, -1) {}

    int size() const {
        return _n;
    }

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

    int component_count() const {
        return _component_count;
    }

    int history_size() const {
        return int(history.size());
    }

    void reserve_history(int count) {
        assert(0 <= count);
        history.reserve(count);
    }

    int leader(int vertex) const {
        assert(0 <= vertex && vertex < _n);
        while (parent_or_size[vertex] >= 0) vertex = parent_or_size[vertex];
        return vertex;
    }

    bool same(int first, int second) const {
        return leader(first) == leader(second);
    }

    int group_size(int vertex) const {
        return -parent_or_size[leader(vertex)];
    }

    int size(int vertex) const {
        return group_size(vertex);
    }

    bool merge(int first, int second) {
        first = leader(first);
        second = leader(second);
        if (first == second) {
            history.push_back(HistoryEntry{-1, 0, -1, 0});
            return false;
        }
        if (-parent_or_size[first] < -parent_or_size[second]) {
            std::swap(first, second);
        }
        history.push_back(HistoryEntry{
            first, parent_or_size[first], second, parent_or_size[second]
        });
        parent_or_size[first] += parent_or_size[second];
        parent_or_size[second] = first;
        _component_count--;
        return true;
    }

    bool undo() {
        if (history.empty()) return false;
        const HistoryEntry entry = history.back();
        history.pop_back();
        if (entry.first == -1) return true;
        parent_or_size[entry.first] = entry.first_value;
        parent_or_size[entry.second] = entry.second_value;
        _component_count++;
        return true;
    }

    int snapshot() const {
        return history_size();
    }

    void rollback(int state) {
        assert(0 <= state && state <= history_size());
        while (history_size() > state) undo();
    }

    std::vector<std::vector<int>> groups() const {
        std::vector<int> leader_buffer(_n);
        std::vector<int> group_sizes(_n, 0);
        for (int vertex = 0; vertex < _n; vertex++) {
            leader_buffer[vertex] = leader(vertex);
            group_sizes[leader_buffer[vertex]]++;
        }
        std::vector<std::vector<int>> result(_n);
        for (int vertex = 0; vertex < _n; vertex++) {
            result[vertex].reserve(group_sizes[vertex]);
        }
        for (int vertex = 0; vertex < _n; vertex++) {
            result[leader_buffer[vertex]].push_back(vertex);
        }
        result.erase(
            std::remove_if(
                result.begin(), result.end(),
                [](const std::vector<int>& group) { return group.empty(); }
            ),
            result.end()
        );
        return result;
    }
};

}  // namespace ds
}  // namespace m1une


#line 10 "ds/dynamic_connectivity/offline_dynamic_connectivity.hpp"

namespace m1une {
namespace ds {

struct OfflineDynamicConnectivity {
   private:
    struct Edge {
        int u;
        int v;
        int begin;
        int end;
        bool alive;
    };

    struct Query {
        int u;
        int v;
        int time;
    };

    int _n;
    int _time = 0;
    std::vector<Edge> _edges;
    std::vector<Query> _queries;

    void dfs(
        const std::vector<int>& offset,
        const std::vector<std::pair<int, int>>& stored_edges,
        const std::vector<int>& query_at,
        std::vector<bool>& answer,
        RollbackDsu& dsu,
        int node,
        int base
    ) const {
        int snapshot = dsu.snapshot();
        for (int i = offset[node]; i < offset[node + 1]; i++) {
            auto [u, v] = stored_edges[i];
            dsu.merge(u, v);
        }
        if (node >= base) {
            int query_id = query_at[node - base];
            if (query_id != -1) {
                const Query& query = _queries[query_id];
                answer[query_id] = dsu.same(query.u, query.v);
            }
        } else {
            dfs(offset, stored_edges, query_at, answer, dsu, 2 * node, base);
            dfs(offset, stored_edges, query_at, answer, dsu, 2 * node + 1, base);
        }
        dsu.rollback(snapshot);
    }

   public:
    OfflineDynamicConnectivity() : OfflineDynamicConnectivity(0) {}

    explicit OfflineDynamicConnectivity(int n) : _n(n) {
        assert(0 <= n);
    }

    int size() const {
        return _n;
    }

    int edge_count() const {
        return int(_edges.size());
    }

    int query_count() const {
        return int(_queries.size());
    }

    int operation_count() const {
        return _time;
    }

    void reserve_edges(int count) {
        assert(0 <= count);
        _edges.reserve(count);
    }

    void reserve_queries(int count) {
        assert(0 <= count);
        _queries.reserve(count);
    }

    bool edge_alive(int edge_id) const {
        assert(0 <= edge_id && edge_id < int(_edges.size()));
        return _edges[edge_id].alive;
    }

    int add_edge(int u, int v) {
        assert(0 <= u && u < _n);
        assert(0 <= v && v < _n);
        int edge_id = int(_edges.size());
        _edges.push_back(Edge{u, v, _time, -1, true});
        _time++;
        return edge_id;
    }

    bool erase_edge(int edge_id) {
        assert(0 <= edge_id && edge_id < int(_edges.size()));
        Edge& edge = _edges[edge_id];
        if (!edge.alive) return false;
        edge.end = _time;
        edge.alive = false;
        _time++;
        return true;
    }

    int add_query(int u, int v) {
        assert(0 <= u && u < _n);
        assert(0 <= v && v < _n);
        int query_id = int(_queries.size());
        _queries.push_back(Query{u, v, _time});
        _time++;
        return query_id;
    }

    std::vector<bool> solve() const {
        std::vector<bool> answer(_queries.size(), false);
        if (_queries.empty()) return answer;
        if (_edges.empty()) {
            for (int query_id = 0; query_id < int(_queries.size()); query_id++) {
                answer[query_id] = _queries[query_id].u == _queries[query_id].v;
            }
            return answer;
        }

        int base = 1;
        while (base < _time) base *= 2;
        int node_count = 2 * base;
        std::vector<int> count(node_count, 0);
        for (const Edge& edge : _edges) {
            int end = edge.alive ? _time : edge.end;
            if (edge.begin < end && edge.u != edge.v) {
                int left = edge.begin + base;
                int right = end + base;
                while (left < right) {
                    if (left & 1) count[left++]++;
                    if (right & 1) count[--right]++;
                    left /= 2;
                    right /= 2;
                }
            }
        }
        std::vector<int> offset(node_count + 1, 0);
        for (int node = 1; node < node_count; node++) offset[node + 1] = offset[node] + count[node];
        std::vector<int> cursor = offset;
        std::vector<std::pair<int, int>> stored_edges(offset[node_count]);
        for (const Edge& edge : _edges) {
            int end = edge.alive ? _time : edge.end;
            if (edge.begin >= end || edge.u == edge.v) continue;
            int left = edge.begin + base;
            int right = end + base;
            while (left < right) {
                if (left & 1) stored_edges[cursor[left]++] = {edge.u, edge.v}, left++;
                if (right & 1) --right, stored_edges[cursor[right]++] = {edge.u, edge.v};
                left /= 2;
                right /= 2;
            }
        }
        std::vector<int> query_at(base, -1);
        for (int query_id = 0; query_id < int(_queries.size()); query_id++) {
            query_at[_queries[query_id].time] = query_id;
        }
        RollbackDsu dsu(_n);
        dsu.reserve_history(int(std::min<std::size_t>(_n, stored_edges.size())));
        dfs(offset, stored_edges, query_at, answer, dsu, 1, base);
        return answer;
    }
};

}  // namespace ds
}  // namespace m1une


#line 1 "ds/dynamic_connectivity/online_dynamic_connectivity.hpp"



#line 9 "ds/dynamic_connectivity/online_dynamic_connectivity.hpp"

#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 "ds/dynamic_tree/link_cut_tree.hpp"



#line 5 "ds/dynamic_tree/link_cut_tree.hpp"
#include <concepts>
#line 9 "ds/dynamic_tree/link_cut_tree.hpp"

#line 1 "monoid/concept.hpp"



#line 5 "monoid/concept.hpp"

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 11 "ds/dynamic_tree/link_cut_tree.hpp"

namespace m1une {
namespace ds {

template <m1une::monoid::IsCommutativeGroup Group>
struct LinkCutTree {
    using T = typename Group::value_type;

   private:
    struct Node {
        int left = -1;
        int right = -1;
        int parent = -1;
        bool rev = false;
        int size = 1;
        int virtual_size = 0;
        int all_size = 1;
        T value = Group::id();
        T prod = Group::id();
        T rev_prod = Group::id();
        T virtual_prod = Group::id();
        T all_prod = Group::id();
    };

    struct EdgeInfo {
        int u = -1;
        int v = -1;
        int node = -1;
        bool alive = false;
    };

    std::vector<Node> _nodes;
    std::vector<EdgeInfo> _edges;
    std::vector<int> _path_buffer;

    static T make_node_value(const T& value, int) {
        return value;
    }

    static T make_node_value(T&& value, int) {
        return std::move(value);
    }

    template <class U>
    requires (!std::same_as<U, T>) && (
        requires(U x) { Group::make(x); } ||
        requires(U x, int i) { Group::make(x, i); } ||
        std::convertible_to<U, T>
    )
    static T make_node_value(const U& value, int index) {
        if constexpr (requires(U x) { Group::make(x); }) {
            return Group::make(value);
        } else if constexpr (requires(U x, int i) { Group::make(x, i); }) {
            return Group::make(value, index);
        } else {
            return static_cast<T>(value);
        }
    }

    int child_size(int node) const {
        return node == -1 ? 0 : _nodes[node].size;
    }

    int child_all_size(int node) const {
        return node == -1 ? 0 : _nodes[node].all_size;
    }

    T child_prod(int node) const {
        return node == -1 ? Group::id() : _nodes[node].prod;
    }

    T child_rev_prod(int node) const {
        return node == -1 ? Group::id() : _nodes[node].rev_prod;
    }

    T child_all_prod(int node) const {
        return node == -1 ? Group::id() : _nodes[node].all_prod;
    }

    T node_subtree_prod(int node) const {
        const Node& x = _nodes[node];
        return Group::op(x.value, x.virtual_prod);
    }

    int node_subtree_size(int node) const {
        return 1 + _nodes[node].virtual_size;
    }

    bool is_splay_root(int node) const {
        int parent = _nodes[node].parent;
        return parent == -1 || (_nodes[parent].left != node && _nodes[parent].right != node);
    }

    void update(int node) {
        Node& x = _nodes[node];
        x.size = 1 + child_size(x.left) + child_size(x.right);
        x.all_size = 1 + x.virtual_size + child_all_size(x.left) + child_all_size(x.right);
        x.prod = Group::op(Group::op(child_prod(x.left), x.value), child_prod(x.right));
        x.rev_prod = Group::op(Group::op(child_rev_prod(x.right), x.value), child_rev_prod(x.left));
        x.all_prod = Group::op(Group::op(child_all_prod(x.left), x.value),
                                Group::op(x.virtual_prod, child_all_prod(x.right)));
    }

    void add_virtual_child(int node, int child) {
        if (child == -1) return;
        Node& x = _nodes[node];
        x.virtual_size += _nodes[child].all_size;
        x.virtual_prod = Group::op(x.virtual_prod, _nodes[child].all_prod);
    }

    void remove_virtual_child(int node, int child) {
        if (child == -1) return;
        Node& x = _nodes[node];
        x.virtual_size -= _nodes[child].all_size;
        x.virtual_prod = Group::op(x.virtual_prod, Group::inv(_nodes[child].all_prod));
    }

    void apply_reverse(int node) {
        if (node == -1) return;
        Node& x = _nodes[node];
        std::swap(x.left, x.right);
        std::swap(x.prod, x.rev_prod);
        x.rev = !x.rev;
    }

    void push(int node) {
        if (node == -1 || !_nodes[node].rev) return;
        apply_reverse(_nodes[node].left);
        apply_reverse(_nodes[node].right);
        _nodes[node].rev = false;
    }

    void push_to(int node) {
        _path_buffer.clear();
        int cur = node;
        _path_buffer.push_back(cur);
        while (!is_splay_root(cur)) {
            cur = _nodes[cur].parent;
            _path_buffer.push_back(cur);
        }
        for (int i = int(_path_buffer.size()) - 1; i >= 0; i--) push(_path_buffer[i]);
    }

    void rotate(int node) {
        int parent = _nodes[node].parent;
        int grand = _nodes[parent].parent;
        bool is_right = _nodes[parent].right == node;
        int middle = is_right ? _nodes[node].left : _nodes[node].right;

        if (!is_splay_root(parent)) {
            if (_nodes[grand].left == parent) {
                _nodes[grand].left = node;
            } else {
                _nodes[grand].right = node;
            }
        }
        _nodes[node].parent = grand;

        if (is_right) {
            _nodes[node].left = parent;
            _nodes[parent].right = middle;
        } else {
            _nodes[node].right = parent;
            _nodes[parent].left = middle;
        }
        if (middle != -1) _nodes[middle].parent = parent;
        _nodes[parent].parent = node;

        update(parent);
        update(node);
    }

    void splay(int node) {
        push_to(node);
        while (!is_splay_root(node)) {
            int parent = _nodes[node].parent;
            int grand = _nodes[parent].parent;
            if (!is_splay_root(parent)) {
                bool zig_zig = (_nodes[parent].left == node) == (_nodes[grand].left == parent);
                rotate(zig_zig ? parent : node);
            }
            rotate(node);
        }
    }

    int access(int node) {
        int last = -1;
        for (int cur = node; cur != -1; cur = _nodes[cur].parent) {
            splay(cur);
            add_virtual_child(cur, _nodes[cur].right);
            remove_virtual_child(cur, last);
            _nodes[cur].right = last;
            if (last != -1) _nodes[last].parent = cur;
            update(cur);
            last = cur;
        }
        splay(node);
        return last;
    }

    void check_vertex(int v) const {
        assert(0 <= v && v < int(_nodes.size()));
    }

    void check_edge(int edge_id) const {
        assert(0 <= edge_id && edge_id < int(_edges.size()));
    }

   public:
    LinkCutTree() = default;

    explicit LinkCutTree(int n) {
        assert(0 <= n);
        _nodes.reserve(n);
        for (int i = 0; i < n; i++) add_vertex();
    }

    explicit LinkCutTree(const std::vector<T>& values) {
        _nodes.reserve(values.size());
        for (int i = 0; i < int(values.size()); i++) add_vertex(values[i]);
    }

    explicit LinkCutTree(std::vector<T>&& values) {
        _nodes.reserve(values.size());
        for (int i = 0; i < int(values.size()); i++) add_vertex(std::move(values[i]));
    }

    template <class U>
    requires (!std::same_as<U, T>) && (
        requires(U x) { Group::make(x); } ||
        requires(U x, int i) { Group::make(x, i); } ||
        std::convertible_to<U, T>
    )
    explicit LinkCutTree(const std::vector<U>& values) {
        _nodes.reserve(values.size());
        for (int i = 0; i < int(values.size()); i++) add_vertex(make_node_value(values[i], i));
    }

    int size() const {
        return int(_nodes.size());
    }

    bool empty() const {
        return _nodes.empty();
    }

    int add_vertex(const T& value = Group::id()) {
        Node node;
        node.value = value;
        node.prod = value;
        node.rev_prod = value;
        node.all_prod = value;
        _nodes.push_back(std::move(node));
        return int(_nodes.size()) - 1;
    }

    int add_vertex(T&& value) {
        Node node;
        node.value = std::move(value);
        node.prod = node.value;
        node.rev_prod = node.value;
        node.all_prod = node.value;
        _nodes.push_back(std::move(node));
        return int(_nodes.size()) - 1;
    }

    template <class U>
    requires (!std::same_as<std::remove_cvref_t<U>, T>) && (
        requires(U x) { Group::make(x); } ||
        requires(U x, int i) { Group::make(x, i); } ||
        std::convertible_to<U, T>
    )
    int add_vertex(const U& value) {
        return add_vertex(make_node_value(value, size()));
    }

    int edge_count() const {
        return int(_edges.size());
    }

    bool edge_alive(int edge_id) const {
        check_edge(edge_id);
        return _edges[edge_id].alive;
    }

    int edge_node(int edge_id) const {
        check_edge(edge_id);
        return _edges[edge_id].node;
    }

    std::pair<int, int> edge_endpoints(int edge_id) const {
        check_edge(edge_id);
        return {_edges[edge_id].u, _edges[edge_id].v};
    }

    const T& get(int v) const {
        check_vertex(v);
        return _nodes[v].value;
    }

    const T& operator[](int v) const {
        return get(v);
    }

    void set(int v, const T& value) {
        check_vertex(v);
        access(v);
        _nodes[v].value = value;
        update(v);
    }

    void set(int v, T&& value) {
        check_vertex(v);
        access(v);
        _nodes[v].value = std::move(value);
        update(v);
    }

    template <class U>
    requires (!std::same_as<std::remove_cvref_t<U>, T>) && (
        requires(U x) { Group::make(x); } ||
        requires(U x, int i) { Group::make(x, i); } ||
        std::convertible_to<U, T>
    )
    void set(int v, const U& value) {
        set(v, make_node_value(value, v));
    }

    // Makes `v` the represented root of its component.
    void evert(int v) {
        check_vertex(v);
        access(v);
        apply_reverse(v);
    }

    // Alias for `evert(v)`; changes the represented root to `v`.
    void reroot(int v) {
        evert(v);
    }

    // Returns the current represented root of `v`'s component.
    int component_root(int v) {
        check_vertex(v);
        access(v);
        int cur = v;
        push(cur);
        while (_nodes[cur].left != -1) {
            cur = _nodes[cur].left;
            push(cur);
        }
        splay(cur);
        return cur;
    }

    // Alias for `component_root(v)`.
    int root(int v) {
        return component_root(v);
    }

    bool connected(int u, int v) {
        check_vertex(u);
        check_vertex(v);
        if (u == v) return true;
        return component_root(u) == component_root(v);
    }

    bool same(int u, int v) {
        return connected(u, v);
    }

    // Links two components. Internally calls `evert(u)`, so the represented root may change.
    bool link(int u, int v) {
        check_vertex(u);
        check_vertex(v);
        if (u == v) return false;
        evert(u);
        if (component_root(v) == u) return false;
        access(v);
        _nodes[u].parent = v;
        add_virtual_child(v, u);
        update(v);
        return true;
    }

    // Links `child` under `parent`. This is the same operation as `link(child, parent)`;
    // it internally calls `evert(child)`, so that side's represented root may change.
    bool link_parent(int child, int parent) {
        return link(child, parent);
    }

    int link_edge(int u, int v, const T& value = Group::id()) {
        check_vertex(u);
        check_vertex(v);
        if (u == v || connected(u, v)) return -1;
        int edge_id = int(_edges.size());
        int node = add_vertex(value);
        _edges.push_back(EdgeInfo{u, v, node, true});
        bool ok1 = link(u, node);
        bool ok2 = link(node, v);
        assert(ok1 && ok2);
        return edge_id;
    }

    int link_edge(int u, int v, T&& value) {
        check_vertex(u);
        check_vertex(v);
        if (u == v || connected(u, v)) return -1;
        int edge_id = int(_edges.size());
        int node = add_vertex(std::move(value));
        _edges.push_back(EdgeInfo{u, v, node, true});
        bool ok1 = link(u, node);
        bool ok2 = link(node, v);
        assert(ok1 && ok2);
        return edge_id;
    }

    template <class U>
    requires (!std::same_as<std::remove_cvref_t<U>, T>) && (
        requires(U x) { Group::make(x); } ||
        requires(U x, int i) { Group::make(x, i); } ||
        std::convertible_to<U, T>
    )
    int link_edge(int u, int v, const U& value) {
        check_vertex(u);
        check_vertex(v);
        if (u == v || connected(u, v)) return -1;
        return link_edge(u, v, make_node_value(value, size()));
    }

    // Cuts edge `(u, v)`. Internally calls `evert(u)`, so the represented root may change.
    bool cut(int u, int v) {
        check_vertex(u);
        check_vertex(v);
        if (u == v) return false;
        evert(u);
        access(v);
        if (_nodes[v].left != u || _nodes[u].right != -1) return false;
        _nodes[v].left = -1;
        _nodes[u].parent = -1;
        update(v);
        return true;
    }

    // Cuts the parent edge of `v` in the current represented-root orientation.
    // Unlike `cut(u, v)`, this does not call `evert`.
    bool cut_parent(int v) {
        check_vertex(v);
        access(v);
        int left = _nodes[v].left;
        if (left == -1) return false;
        _nodes[v].left = -1;
        _nodes[left].parent = -1;
        update(v);
        return true;
    }

    bool cut_edge(int edge_id) {
        check_edge(edge_id);
        EdgeInfo& edge = _edges[edge_id];
        if (!edge.alive) return false;
        bool ok1 = cut(edge.u, edge.node);
        bool ok2 = cut(edge.node, edge.v);
        if (ok1 && ok2) edge.alive = false;
        return ok1 && ok2;
    }

    const T& get_edge(int edge_id) const {
        return get(edge_node(edge_id));
    }

    void set_edge(int edge_id, const T& value) {
        set(edge_node(edge_id), value);
    }

    void set_edge(int edge_id, T&& value) {
        set(edge_node(edge_id), std::move(value));
    }

    template <class U>
    requires (!std::same_as<std::remove_cvref_t<U>, T>) && (
        requires(U x) { Group::make(x); } ||
        requires(U x, int i) { Group::make(x, i); } ||
        std::convertible_to<U, T>
    )
    void set_edge(int edge_id, const U& value) {
        set(edge_node(edge_id), make_node_value(value, edge_node(edge_id)));
    }

    // Returns the path product from `u` to `v`. Internally calls `evert(u)`,
    // so the represented root may change.
    T prod(int u, int v) {
        check_vertex(u);
        check_vertex(v);
        assert(connected(u, v));
        evert(u);
        access(v);
        return _nodes[v].prod;
    }

    // Alias for `prod(u, v)`. Internally calls `evert(u)`,
    // so the represented root may change.
    T path_prod(int u, int v) {
        return prod(u, v);
    }

    // Returns the number of vertices on path `u`-`v`. Internally calls `evert(u)`,
    // so the represented root may change.
    int path_size(int u, int v) {
        check_vertex(u);
        check_vertex(v);
        assert(connected(u, v));
        evert(u);
        access(v);
        return _nodes[v].size;
    }

    // Returns the `k`-th vertex on path `u`-`v`. Internally calls `evert(u)`,
    // so the represented root may change.
    int kth_vertex(int u, int v, int k) {
        check_vertex(u);
        check_vertex(v);
        assert(connected(u, v));
        evert(u);
        access(v);
        assert(0 <= k && k < _nodes[v].size);

        int cur = v;
        while (true) {
            push(cur);
            int left_size = child_size(_nodes[cur].left);
            if (k < left_size) {
                cur = _nodes[cur].left;
            } else if (k == left_size) {
                splay(cur);
                return cur;
            } else {
                k -= left_size + 1;
                cur = _nodes[cur].right;
            }
        }
    }

    int lca(int u, int v) {
        check_vertex(u);
        check_vertex(v);
        if (!connected(u, v)) return -1;
        if (u == v) return u;
        access(u);
        return access(v);
    }

    // Returns the aggregate of `v`'s subtree when the represented tree is rooted at `root`.
    // Internally calls `evert(root)`, so the represented root may change.
    T subtree_prod(int root, int v) {
        check_vertex(root);
        check_vertex(v);
        assert(connected(root, v));
        evert(root);
        access(v);
        return node_subtree_prod(v);
    }

    // Returns the aggregate of `v`'s subtree with respect to the current represented root.
    T subtree_prod(int v) {
        check_vertex(v);
        access(v);
        return node_subtree_prod(v);
    }

    // Returns the size of `v`'s subtree when the represented tree is rooted at `root`.
    // Internally calls `evert(root)`, so the represented root may change.
    int subtree_size(int root, int v) {
        check_vertex(root);
        check_vertex(v);
        assert(connected(root, v));
        evert(root);
        access(v);
        return node_subtree_size(v);
    }

    // Returns the size of `v`'s subtree with respect to the current represented root.
    int subtree_size(int v) {
        check_vertex(v);
        access(v);
        return node_subtree_size(v);
    }

    // Returns the aggregate of the whole connected component containing `v`.
    T component_prod(int v) {
        int r = root(v);
        return subtree_prod(r, r);
    }

    // Returns the number of vertices in the connected component containing `v`.
    int component_size(int v) {
        int r = root(v);
        return subtree_size(r, r);
    }

    // Returns the child of `root` that lies on path `root`-`v`.
    int child_toward(int root, int v) {
        check_vertex(root);
        check_vertex(v);
        assert(root != v);
        assert(connected(root, v));
        return kth_vertex(root, v, 1);
    }

    // Returns the aggregate of the entire branch of `root` that contains `v`.
    T branch_prod(int root, int v) {
        check_vertex(root);
        check_vertex(v);
        assert(root != v);
        int child = child_toward(root, v);
        return subtree_prod(root, child);
    }

    // Returns the size of the entire branch of `root` that contains `v`.
    int branch_size(int root, int v) {
        check_vertex(root);
        check_vertex(v);
        assert(root != v);
        int child = child_toward(root, v);
        return subtree_size(root, child);
    }

    // Returns the parent of `v` when rooted at `root`, or `-1` if `v == root`.
    int parent(int root, int v) {
        check_vertex(root);
        check_vertex(v);
        if (root == v) return -1;
        assert(connected(root, v));
        int d = path_size(root, v);
        assert(2 <= d);
        return kth_vertex(root, v, d - 2);
    }

    // Returns `v`'s rooted subtree aggregate excluding the child-side subtree.
    T subtree_prod_excluding_child(int root, int v, int child) {
        check_vertex(root);
        check_vertex(v);
        check_vertex(child);
        assert(parent(root, child) == v);
        T whole = subtree_prod(root, v);
        T sub = subtree_prod(root, child);
        return Group::op(whole, Group::inv(sub));
    }

    // Returns `v`'s rooted subtree size excluding the child-side subtree.
    int subtree_size_excluding_child(int root, int v, int child) {
        check_vertex(root);
        check_vertex(v);
        check_vertex(child);
        assert(parent(root, child) == v);
        return subtree_size(root, v) - subtree_size(root, child);
    }
};

}  // namespace ds
}  // namespace m1une


#line 12 "ds/dynamic_connectivity/online_dynamic_connectivity.hpp"

namespace m1une {
namespace ds {

struct OnlineDynamicConnectivity {
   private:
    using Forest = LinkCutTree<m1une::monoid::Add<int>>;

    struct Edge {
        int u;
        int v;
        bool alive;
        bool tree;
        int previous_u = -1;
        int next_u = -1;
        int previous_v = -1;
        int next_v = -1;
    };

    int _n;
    int _component_count;
    int _active_edge_count = 0;
    Forest _forest;
    std::vector<Edge> _edges;
    std::vector<int> _tree_head;
    std::vector<int> _non_tree_head;
    std::vector<std::uint32_t> _visited;
    std::vector<std::uint32_t> _edge_visited;
    std::uint32_t _visit_token = 0;
    std::vector<int> _stack;
    std::vector<int> _component;

    int endpoint_side(const Edge& edge, int v) const {
        return edge.u == v ? 0 : 1;
    }

    int& previous(Edge& edge, int side) {
        return side == 0 ? edge.previous_u : edge.previous_v;
    }

    int& next(Edge& edge, int side) {
        return side == 0 ? edge.next_u : edge.next_v;
    }

    int next(const Edge& edge, int side) const {
        return side == 0 ? edge.next_u : edge.next_v;
    }

    void insert_one(std::vector<int>& head, int edge_id, int v, int side) {
        Edge& edge = _edges[edge_id];
        int old_head = head[v];
        previous(edge, side) = -1;
        next(edge, side) = old_head;
        if (old_head != -1) {
            Edge& old_edge = _edges[old_head];
            previous(old_edge, endpoint_side(old_edge, v)) = edge_id;
        }
        head[v] = edge_id;
    }

    void erase_one(std::vector<int>& head, int edge_id, int v, int side) {
        Edge& edge = _edges[edge_id];
        int previous_id = previous(edge, side);
        int next_id = next(edge, side);
        if (previous_id == -1) {
            head[v] = next_id;
        } else {
            Edge& previous_edge = _edges[previous_id];
            next(previous_edge, endpoint_side(previous_edge, v)) = next_id;
        }
        if (next_id != -1) {
            Edge& next_edge = _edges[next_id];
            previous(next_edge, endpoint_side(next_edge, v)) = previous_id;
        }
        previous(edge, side) = -1;
        next(edge, side) = -1;
    }

    void insert_incident(std::vector<int>& head, int edge_id) {
        const Edge& edge = _edges[edge_id];
        int u = edge.u;
        int v = edge.v;
        insert_one(head, edge_id, u, 0);
        if (u != v) insert_one(head, edge_id, v, 1);
    }

    void erase_incident(std::vector<int>& head, int edge_id) {
        const Edge& edge = _edges[edge_id];
        int u = edge.u;
        int v = edge.v;
        erase_one(head, edge_id, u, 0);
        if (u != v) erase_one(head, edge_id, v, 1);
    }

    void make_tree_edge(int edge_id) {
        Edge& edge = _edges[edge_id];
        assert(edge.alive && !edge.tree && edge.u != edge.v);
        erase_incident(_non_tree_head, edge_id);
        bool linked = _forest.link(edge.u, edge.v);
        assert(linked);
        edge.tree = true;
        insert_incident(_tree_head, edge_id);
        _component_count--;
    }

    void collect_component(int start) {
        _visit_token++;
        if (_visit_token == 0) {
            std::fill(_visited.begin(), _visited.end(), 0);
            std::fill(_edge_visited.begin(), _edge_visited.end(), 0);
            _visit_token = 1;
        }
        _stack.clear();
        _component.clear();
        _visited[start] = _visit_token;
        _stack.push_back(start);
        while (!_stack.empty()) {
            int v = _stack.back();
            _stack.pop_back();
            _component.push_back(v);
            for (int edge_id = _tree_head[v]; edge_id != -1;) {
                const Edge& edge = _edges[edge_id];
                int edge_side = endpoint_side(edge, v);
                edge_id = next(edge, edge_side);
                int to = edge.u ^ edge.v ^ v;
                if (_visited[to] == _visit_token) continue;
                _visited[to] = _visit_token;
                _stack.push_back(to);
            }
        }
    }

    void reconnect(int u, int v) {
        int start = _forest.component_size(u) <= _forest.component_size(v) ? u : v;
        collect_component(start);
        int replacement = -1;
        for (int x : _component) {
            for (int edge_id = _non_tree_head[x]; edge_id != -1;) {
                const Edge& edge = _edges[edge_id];
                int edge_side = endpoint_side(edge, x);
                int current_edge = edge_id;
                edge_id = next(edge, edge_side);
                if (_edge_visited[current_edge] == _visit_token) continue;
                _edge_visited[current_edge] = _visit_token;
                if (_visited[edge.u] != _visit_token || _visited[edge.v] != _visit_token) {
                    replacement = current_edge;
                    break;
                }
            }
            if (replacement != -1) break;
        }
        if (replacement != -1) make_tree_edge(replacement);
    }

   public:
    OnlineDynamicConnectivity() : OnlineDynamicConnectivity(0) {}

    explicit OnlineDynamicConnectivity(int n)
        : _n(n),
          _component_count(n),
          _forest(n),
          _tree_head(n, -1),
          _non_tree_head(n, -1),
          _visited(n, 0) {
        assert(0 <= n);
    }

    int size() const {
        return _n;
    }

    int edge_count() const {
        return int(_edges.size());
    }

    int active_edge_count() const {
        return _active_edge_count;
    }

    int component_count() const {
        return _component_count;
    }

    void reserve_edges(int count) {
        assert(0 <= count);
        _edges.reserve(count);
        _edge_visited.reserve(count);
    }

    bool edge_alive(int edge_id) const {
        assert(0 <= edge_id && edge_id < int(_edges.size()));
        return _edges[edge_id].alive;
    }

    std::pair<int, int> edge_endpoints(int edge_id) const {
        assert(0 <= edge_id && edge_id < int(_edges.size()));
        return {_edges[edge_id].u, _edges[edge_id].v};
    }

    bool connected(int u, int v) {
        assert(0 <= u && u < _n);
        assert(0 <= v && v < _n);
        return _forest.connected(u, v);
    }

    bool same(int u, int v) {
        return connected(u, v);
    }

    int component_size(int v) {
        assert(0 <= v && v < _n);
        return _forest.component_size(v);
    }

    int add_edge(int u, int v) {
        assert(0 <= u && u < _n);
        assert(0 <= v && v < _n);
        bool is_tree = u != v && _forest.link(u, v);
        int edge_id = int(_edges.size());
        Edge edge;
        edge.u = u;
        edge.v = v;
        edge.alive = true;
        edge.tree = is_tree;
        _edges.push_back(edge);
        _edge_visited.push_back(0);
        _active_edge_count++;
        if (is_tree) {
            insert_incident(_tree_head, edge_id);
            _component_count--;
        } else {
            insert_incident(_non_tree_head, edge_id);
        }
        return edge_id;
    }

    bool erase_edge(int edge_id) {
        assert(0 <= edge_id && edge_id < int(_edges.size()));
        Edge& edge = _edges[edge_id];
        if (!edge.alive) return false;
        edge.alive = false;
        _active_edge_count--;
        if (!edge.tree) {
            erase_incident(_non_tree_head, edge_id);
            return true;
        }

        erase_incident(_tree_head, edge_id);
        bool cut = _forest.cut(edge.u, edge.v);
        assert(cut);
        _component_count++;
        reconnect(edge.u, edge.v);
        return true;
    }
};

}  // namespace ds
}  // namespace m1une


#line 6 "ds/dynamic_connectivity/all.hpp"


#line 11 "verify/ds/dynamic_connectivity/dynamic_connectivity.test.cpp"

struct NaiveDynamicGraph {
    struct Edge {
        int u;
        int v;
        bool alive;
    };

    int n;
    std::vector<Edge> edges;

    explicit NaiveDynamicGraph(int n) : n(n) {}

    int add_edge(int u, int v) {
        int id = int(edges.size());
        edges.push_back(Edge{u, v, true});
        return id;
    }

    bool erase_edge(int id) {
        if (!edges[id].alive) return false;
        edges[id].alive = false;
        return true;
    }

    std::vector<int> component(int start) const {
        std::vector<std::vector<int>> graph(n);
        for (const Edge& edge : edges) {
            if (!edge.alive || edge.u == edge.v) continue;
            graph[edge.u].push_back(edge.v);
            graph[edge.v].push_back(edge.u);
        }
        std::vector<int> visited(n, false);
        std::queue<int> queue;
        std::vector<int> vertices;
        visited[start] = true;
        queue.push(start);
        while (!queue.empty()) {
            int v = queue.front();
            queue.pop();
            vertices.push_back(v);
            for (int to : graph[v]) {
                if (visited[to]) continue;
                visited[to] = true;
                queue.push(to);
            }
        }
        return vertices;
    }

    bool connected(int u, int v) const {
        std::vector<int> vertices = component(u);
        for (int x : vertices) {
            if (x == v) return true;
        }
        return false;
    }

    int component_count() const {
        std::vector<bool> visited(n, false);
        int result = 0;
        for (int v = 0; v < n; v++) {
            if (visited[v]) continue;
            result++;
            for (int x : component(v)) visited[x] = true;
        }
        return result;
    }
};

void test_online_basic() {
    m1une::ds::OnlineDynamicConnectivity graph(4);
    graph.reserve_edges(8);
    int e01 = graph.add_edge(0, 1);
    int e12 = graph.add_edge(1, 2);
    int e02 = graph.add_edge(0, 2);
    int loop = graph.add_edge(3, 3);
    assert(graph.connected(0, 2));
    assert(graph.component_size(0) == 3);
    assert(graph.component_count() == 2);
    assert(graph.active_edge_count() == 4);

    assert(graph.erase_edge(e12));
    assert(graph.connected(0, 2));
    assert(graph.erase_edge(e02));
    assert(!graph.connected(0, 2));
    assert(graph.component_count() == 3);
    assert(!graph.erase_edge(e02));
    assert(graph.erase_edge(loop));
    assert(graph.erase_edge(e01));
    assert(graph.component_count() == 4);
}

void test_offline_basic() {
    m1une::ds::OfflineDynamicConnectivity graph(3);
    graph.reserve_edges(8);
    graph.reserve_queries(8);
    int e01 = graph.add_edge(0, 1);
    int q0 = graph.add_query(0, 2);
    int e12 = graph.add_edge(1, 2);
    int q1 = graph.add_query(0, 2);
    assert(graph.erase_edge(e01));
    int q2 = graph.add_query(0, 2);
    assert(!graph.erase_edge(e01));
    int parallel = graph.add_edge(1, 2);
    int q3 = graph.add_query(1, 2);
    assert(graph.erase_edge(e12));
    int q4 = graph.add_query(1, 2);
    assert(graph.erase_edge(parallel));
    int q5 = graph.add_query(1, 2);

    std::vector<bool> answer = graph.solve();
    assert(!answer[q0]);
    assert(answer[q1]);
    assert(!answer[q2]);
    assert(answer[q3]);
    assert(answer[q4]);
    assert(!answer[q5]);
    assert(answer == graph.solve());

    int restored = graph.add_edge(0, 2);
    int q6 = graph.add_query(0, 2);
    answer = graph.solve();
    assert(answer[q6]);
    assert(graph.erase_edge(restored));
}

void test_online_random() {
    std::mt19937 random(123456789);
    for (int test = 0; test < 80; test++) {
        int n = 1 + random() % 15;
        m1une::ds::OnlineDynamicConnectivity graph(n);
        NaiveDynamicGraph naive(n);
        std::vector<int> active;
        for (int operation = 0; operation < 1000; operation++) {
            int type = random() % 5;
            if (type <= 1 || active.empty()) {
                int u = random() % n;
                int v = random() % n;
                int id = graph.add_edge(u, v);
                assert(id == naive.add_edge(u, v));
                active.push_back(id);
            } else if (type == 2) {
                int index = random() % active.size();
                int id = active[index];
                std::swap(active[index], active.back());
                active.pop_back();
                assert(graph.erase_edge(id));
                assert(naive.erase_edge(id));
            } else {
                int u = random() % n;
                int v = random() % n;
                assert(graph.connected(u, v) == naive.connected(u, v));
                assert(graph.component_size(u) == int(naive.component(u).size()));
            }
            assert(graph.active_edge_count() == int(active.size()));
            assert(graph.component_count() == naive.component_count());
        }
    }
}

void test_offline_random() {
    std::mt19937 random(987654321);
    for (int test = 0; test < 100; test++) {
        int n = 1 + random() % 12;
        m1une::ds::OfflineDynamicConnectivity graph(n);
        NaiveDynamicGraph naive(n);
        std::vector<int> active;
        std::vector<bool> expected;
        for (int operation = 0; operation < 500; operation++) {
            int type = random() % 4;
            if (type == 0 || active.empty()) {
                int u = random() % n;
                int v = random() % n;
                int id = graph.add_edge(u, v);
                assert(id == naive.add_edge(u, v));
                active.push_back(id);
            } else if (type == 1) {
                int index = random() % active.size();
                int id = active[index];
                std::swap(active[index], active.back());
                active.pop_back();
                assert(graph.erase_edge(id));
                assert(naive.erase_edge(id));
            } else {
                int u = random() % n;
                int v = random() % n;
                assert(graph.add_query(u, v) == int(expected.size()));
                expected.push_back(naive.connected(u, v));
            }
        }
        assert(graph.solve() == expected);
    }
}

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

    test_online_basic();
    test_offline_basic();
    test_online_random();
    test_offline_random();

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