firiexp's Library

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

View the Project on GitHub firiexp/library

:heavy_check_mark: test/yosupo_dynamic_graph_vertex_add_component_sum_offlinedynamicconnectivity.test.cpp

Depends on

Code

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

#include <algorithm>
#include <map>
#include <stack>
#include <type_traits>
#include <utility>
#include <vector>
using namespace std;

#include <cstdio>
#include <cstring>
#include <string>
#include <type_traits>

#include "../util/fastio.cpp"
#include "../graph/offlinedynamicconnectivity.cpp"

struct RollbackUnionFindComponentSum {
    struct History {
        int child, parent;
        int parent_size, child_size;
        long long parent_sum, child_sum;
    };

    vector<int> parent_or_size;
    vector<long long> comp_sum;
    vector<History> history;

    explicit RollbackUnionFindComponentSum(int n, const vector<long long> &a)
        : parent_or_size(n, -1), comp_sum(a) {}

    int root(int v) const {
        while (parent_or_size[v] >= 0) v = parent_or_size[v];
        return v;
    }

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

    void rollback(int snap) {
        while ((int)history.size() > snap) {
            auto h = history.back();
            history.pop_back();
            if (h.parent == -1) continue;
            parent_or_size[h.parent] = h.parent_size;
            parent_or_size[h.child] = h.child_size;
            comp_sum[h.parent] = h.parent_sum;
            comp_sum[h.child] = h.child_sum;
        }
    }

    void unite(int a, int b) {
        a = root(a), b = root(b);
        if (a == b) {
            history.push_back({-1, -1, 0, 0, 0, 0});
            return;
        }
        if (parent_or_size[a] > parent_or_size[b]) swap(a, b);
        history.push_back({b, a, parent_or_size[a], parent_or_size[b], comp_sum[a], comp_sum[b]});
        parent_or_size[a] += parent_or_size[b];
        parent_or_size[b] = a;
        comp_sum[a] += comp_sum[b];
    }

    void add_value(int v, long long x) {
        int r = root(v);
        history.push_back({r, r, parent_or_size[r], parent_or_size[r], comp_sum[r], comp_sum[r]});
        comp_sum[r] += x;
    }

    long long get_sum(int v) const {
        return comp_sum[root(v)];
    }
};

int main() {
    Scanner sc;
    Printer pr;

    int n, q;
    sc.read(n, q);
    vector<long long> a(n);
    for (auto &x : a) sc.read(x);

    OfflineDynamicConnectivity dc(n, q);
    struct AddEvent {
        int v;
        long long x;
    };
    vector<vector<AddEvent>> seg_adds(2 * dc.sz);
    vector<int> type(q), query_vertex(q, -1);

    auto add_segment = [&](int l, int r, const AddEvent &event) {
        for (l += dc.sz, r += dc.sz; l < r; l >>= 1, r >>= 1) {
            if (l & 1) seg_adds[l++].push_back(event);
            if (r & 1) seg_adds[--r].push_back(event);
        }
    };

    for (int t = 0; t < q; ++t) {
        sc.read(type[t]);
        if (type[t] == 0) {
            int u, v;
            sc.read(u, v);
            dc.insert(t, u, v);
        } else if (type[t] == 1) {
            int u, v;
            sc.read(u, v);
            dc.erase(t, u, v);
        } else if (type[t] == 2) {
            int v;
            long long x;
            sc.read(v, x);
            add_segment(t, q, {v, x});
        } else {
            sc.read(query_vertex[t]);
        }
    }
    dc.build();

    RollbackUnionFindComponentSum uf(n, a);
    vector<int> snaps;
    vector<long long> ans;
    ans.reserve(q);

    dc.dfs(
        [&](int k, const vector<pair<int, int>> &edges) {
            snaps.push_back(uf.snapshot());
            for (auto &&[u, v] : edges) uf.unite(u, v);
            for (auto &&event : seg_adds[k]) uf.add_value(event.v, event.x);
        },
        [&](int, const vector<pair<int, int>> &) {
            uf.rollback(snaps.back());
            snaps.pop_back();
        },
        [&](int t) {
            if (type[t] == 3) ans.push_back(uf.get_sum(query_vertex[t]));
        }
    );

    for (auto &&x : ans) pr.println(x);
    return 0;
}
#line 1 "test/yosupo_dynamic_graph_vertex_add_component_sum_offlinedynamicconnectivity.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/dynamic_graph_vertex_add_component_sum"

#include <algorithm>
#include <map>
#include <stack>
#include <type_traits>
#include <utility>
#include <vector>
using namespace std;

#include <cstdio>
#include <cstring>
#include <string>
#line 15 "test/yosupo_dynamic_graph_vertex_add_component_sum_offlinedynamicconnectivity.test.cpp"

#line 1 "util/fastio.cpp"
using namespace std;

extern "C" int fileno(FILE *);
extern "C" int isatty(int);

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

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

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

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

struct FastIoDigitTable {
    char num[40000];

    constexpr FastIoDigitTable() : num() {
        for (int i = 0; i < 10000; ++i) {
            int x = i;
            for (int j = 3; j >= 0; --j) {
                num[i * 4 + j] = char('0' + x % 10);
                x /= 10;
            }
        }
    }
};

struct Scanner {
    static constexpr int BUFSIZE = 1 << 17;
    static constexpr int OFFSET = 64;
    char buf[BUFSIZE + 1];
    int idx, size;
    bool interactive;

    Scanner() : idx(0), size(0), interactive(isatty(fileno(stdin))) {}

    inline void load() {
        int len = size - idx;
        memmove(buf, buf + idx, len);
        if (interactive) {
            if (fgets(buf + len, BUFSIZE + 1 - len, stdin)) size = len + (int)strlen(buf + len);
            else size = len;
        } else {
            size = len + (int)fread(buf + len, 1, BUFSIZE - len, stdin);
        }
        idx = 0;
        buf[size] = 0;
    }

    inline void ensure() {
        if (idx + OFFSET > size) load();
    }

    inline void ensure_interactive() {
        if (idx == size) load();
    }

    inline char skip() {
        if (interactive) {
            ensure_interactive();
            while (buf[idx] && buf[idx] <= ' ') {
                ++idx;
                ensure_interactive();
            }
            return buf[idx++];
        }
        ensure();
        while (buf[idx] && buf[idx] <= ' ') {
            ++idx;
            ensure();
        }
        return buf[idx++];
    }

    template<class T, typename enable_if<is_integral<T>::value, int>::type = 0>
    void read(T &x) {
        if (interactive) {
            char c = skip();
            bool neg = false;
            if constexpr (is_signed<T>::value) {
                if (c == '-') {
                    neg = true;
                    ensure_interactive();
                    c = buf[idx++];
                }
            }
            x = 0;
            while (c >= '0') {
                x = x * 10 + (c & 15);
                ensure_interactive();
                c = buf[idx++];
            }
            if constexpr (is_signed<T>::value) {
                if (neg) x = -x;
            }
            return;
        }
        char c = skip();
        bool neg = false;
        if constexpr (is_signed<T>::value) {
            if (c == '-') {
                neg = true;
                c = buf[idx++];
            }
        }
        x = 0;
        while (c >= '0') {
            x = x * 10 + (c & 15);
            c = buf[idx++];
        }
        if constexpr (is_signed<T>::value) {
            if (neg) x = -x;
        }
    }

    template<class T, typename enable_if<!is_integral<T>::value && !is_fastio_range<T>::value && !is_same<typename decay<T>::type, string>::value && has_fastio_value<T>::value, int>::type = 0>
    void read(T &x) {
        long long v;
        read(v);
        x = T(v);
    }

    template<class Head, class Next, class... Tail>
    void read(Head &head, Next &next, Tail &...tail) {
        read(head);
        read(next, tail...);
    }

    template<class T, class U>
    void read(pair<T, U> &p) {
        read(p.first, p.second);
    }

    template<class T, typename enable_if<is_fastio_range<T>::value && !is_same<typename decay<T>::type, string>::value, int>::type = 0>
    void read(T &a) {
        for (auto &x : a) read(x);
    }

    void read(char &c) {
        c = skip();
    }

    void read(string &s) {
        s.clear();
        if (interactive) {
            ensure_interactive();
            while (buf[idx] && buf[idx] <= ' ') {
                ++idx;
                ensure_interactive();
            }
            while (true) {
                int start = idx;
                while (idx < size && buf[idx] > ' ') ++idx;
                s.append(buf + start, idx - start);
                if (idx < size) break;
                load();
                if (size == 0) break;
            }
            if (idx < size) ++idx;
            return;
        }
        ensure();
        while (buf[idx] && buf[idx] <= ' ') {
            ++idx;
            ensure();
        }
        while (true) {
            int start = idx;
            while (idx < size && buf[idx] > ' ') ++idx;
            s.append(buf + start, idx - start);
            if (idx < size) break;
            load();
        }
        if (idx < size) ++idx;
    }
};

struct Printer {
    static constexpr int BUFSIZE = 1 << 17;
    static constexpr int OFFSET = 64;
    char buf[BUFSIZE];
    int idx;
    bool interactive;
    inline static constexpr FastIoDigitTable table{};

    Printer() : idx(0), interactive(isatty(fileno(stdout))) {}
    ~Printer() { flush(); }

    inline void flush() {
        if (idx) {
            fwrite(buf, 1, idx, stdout);
            idx = 0;
        }
    }

    inline void pc(char c) {
        if (idx > BUFSIZE - OFFSET) flush();
        buf[idx++] = c;
        if (interactive && c == '\n') flush();
    }

    inline void print_range(const char *s, size_t n) {
        size_t pos = 0;
        while (pos < n) {
            if (idx == BUFSIZE) flush();
            size_t chunk = min(n - pos, (size_t)(BUFSIZE - idx));
            memcpy(buf + idx, s + pos, chunk);
            idx += (int)chunk;
            pos += chunk;
        }
    }

    void print(const char *s) {
        print_range(s, strlen(s));
    }

    void print(const string &s) {
        print_range(s.data(), s.size());
    }

    void print(char c) {
        pc(c);
    }

    void print(bool b) {
        pc(char('0' + (b ? 1 : 0)));
    }

    template<class T, typename enable_if<is_integral<T>::value && !is_same<T, bool>::value, int>::type = 0>
    void print(T x) {
        if (idx > BUFSIZE - 100) flush();
        using U = typename make_unsigned<T>::type;
        U y;
        if constexpr (is_signed<T>::value) {
            if (x < 0) {
                buf[idx++] = '-';
                y = U(0) - static_cast<U>(x);
            } else {
                y = static_cast<U>(x);
            }
        } else {
            y = x;
        }
        if (y == 0) {
            buf[idx++] = '0';
            return;
        }
        static constexpr int TMP_SIZE = sizeof(U) * 10 / 4;
        char tmp[TMP_SIZE];
        int pos = TMP_SIZE;
        while (y >= 10000) {
            pos -= 4;
            memcpy(tmp + pos, table.num + (y % 10000) * 4, 4);
            y /= 10000;
        }
        if (y >= 1000) {
            memcpy(buf + idx, table.num + (y << 2), 4);
            idx += 4;
        } else if (y >= 100) {
            memcpy(buf + idx, table.num + (y << 2) + 1, 3);
            idx += 3;
        } else if (y >= 10) {
            unsigned q = (unsigned(y) * 205) >> 11;
            buf[idx] = char('0' + q);
            buf[idx + 1] = char('0' + (unsigned(y) - q * 10));
            idx += 2;
        } else {
            buf[idx++] = char('0' + y);
        }
        memcpy(buf + idx, tmp + pos, TMP_SIZE - pos);
        idx += TMP_SIZE - pos;
    }

    template<class T, typename enable_if<!is_integral<T>::value && !is_fastio_range<T>::value && !is_same<typename decay<T>::type, string>::value && has_fastio_value<T>::value, int>::type = 0>
    void print(const T &x) {
        print(x.value());
    }

    template<class T, typename enable_if<is_fastio_range<T>::value && !is_same<typename decay<T>::type, string>::value, int>::type = 0>
    void print(const T &a) {
        bool first = true;
        for (auto &&x : a) {
            if (!first) pc(' ');
            first = false;
            print(x);
        }
    }

    template<class T>
    void println(const T &x) {
        print(x);
        pc('\n');
    }

    template<class Head, class... Tail>
    void println(const Head &head, const Tail &...tail) {
        print(head);
        ((pc(' '), print(tail)), ...);
        pc('\n');
    }

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

template<class T>
Scanner &operator>>(Scanner &in, T &x) {
    in.read(x);
    return in;
}

template<class T>
Printer &operator<<(Printer &out, const T &x) {
    out.print(x);
    return out;
}

/**
 * @brief 高速入出力(Fast IO)
 */
#line 1 "graph/offlinedynamicconnectivity.cpp"
using namespace std;

#line 1 "datastructure/undoableunionfind.cpp"
class UndoableUnionFind {
    stack<pair<int, int>> hist;
    int forest_size;
    int snap;

public:
    vector<int> uni;

    explicit UndoableUnionFind(int sz) : forest_size(sz), snap(0), uni(sz, -1) {}

    int root(int a) {
        if (uni[a] < 0) return a;
        return root(uni[a]);
    }

    bool same(int a, int b) {
        return root(a) == root(b);
    }

    bool unite(int a, int b) {
        a = root(a);
        b = root(b);
        hist.emplace(a, uni[a]);
        hist.emplace(b, uni[b]);
        if (a == b) return false;
        if (uni[a] > uni[b]) swap(a, b);
        uni[a] += uni[b];
        uni[b] = a;
        forest_size--;
        return true;
    }

    int size() { return forest_size; }
    int size(int i) { return -uni[root(i)]; }

    int get_state() const {
        return int(hist.size() >> 1);
    }

    void undo() {
        int a = hist.top().first;
        int ua = hist.top().second;
        hist.pop();
        int b = hist.top().first;
        int ub = hist.top().second;
        hist.pop();
        if (a != b) forest_size++;
        uni[a] = ua;
        uni[b] = ub;
    }

    void snapshot() {
        snap = get_state();
    }

    void rollback(int state = -1) {
        if (state == -1) state = snap;
        while (get_state() > state) undo();
    }
};

/**
 * @brief Undoable Union Find
 */
#line 4 "graph/offlinedynamicconnectivity.cpp"

struct OfflineDynamicConnectivity {
    int n, q, sz;
    UndoableUnionFind uf;
    vector<vector<pair<int, int>>> seg;
    vector<pair<pair<int, int>, pair<int, int>>> pend;
    map<pair<int, int>, int> cnt, appear;

    explicit OfflineDynamicConnectivity(int n, int q) : n(n), q(q), uf(n) {
        sz = 1;
        while (sz < q) sz <<= 1;
        seg.resize(2 * sz);
    }

    void add_segment(int l, int r, const pair<int, int> &e) {
        for (l += sz, r += sz; l < r; l >>= 1, r >>= 1) {
            if (l & 1) seg[l++].push_back(e);
            if (r & 1) seg[--r].push_back(e);
        }
    }

    void insert(int t, int a, int b) {
        auto e = minmax(a, b);
        if (cnt[e]++ == 0) appear[e] = t;
    }

    void erase(int t, int a, int b) {
        auto e = minmax(a, b);
        if (--cnt[e] == 0) {
            pend.emplace_back(make_pair(appear[e], t), e);
            appear.erase(e);
        }
    }

    void build() {
        for (auto &&[e, c] : cnt) {
            if (!c) continue;
            pend.emplace_back(make_pair(appear[e], q), e);
        }
        for (auto &&[range, e] : pend) add_segment(range.first, range.second, e);
    }

    template <class Enter, class Leave, class Leaf>
    void dfs(const Enter &enter, const Leave &leave, const Leaf &leaf, int k = 1) {
        enter(k, seg[k]);
        if (k < sz) {
            dfs(enter, leave, leaf, k << 1);
            dfs(enter, leave, leaf, k << 1 | 1);
        } else if (k - sz < q) {
            leaf(k - sz);
        }
        leave(k, seg[k]);
    }

    template <class F>
    void run(const F &f) {
        dfs(
            [&](int, const vector<pair<int, int>> &edges) {
                for (auto &&[u, v] : edges) uf.unite(u, v);
            },
            [&](int, const vector<pair<int, int>> &edges) {
                for (int i = 0; i < (int)edges.size(); ++i) uf.undo();
            },
            [&](int t) {
                if constexpr (is_invocable_v<F, int, UndoableUnionFind &>) {
                    f(t, uf);
                } else {
                    f(t);
                }
            }
        );
    }
};

/**
 * @brief Offline Dynamic Connectivity
 */
#line 18 "test/yosupo_dynamic_graph_vertex_add_component_sum_offlinedynamicconnectivity.test.cpp"

struct RollbackUnionFindComponentSum {
    struct History {
        int child, parent;
        int parent_size, child_size;
        long long parent_sum, child_sum;
    };

    vector<int> parent_or_size;
    vector<long long> comp_sum;
    vector<History> history;

    explicit RollbackUnionFindComponentSum(int n, const vector<long long> &a)
        : parent_or_size(n, -1), comp_sum(a) {}

    int root(int v) const {
        while (parent_or_size[v] >= 0) v = parent_or_size[v];
        return v;
    }

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

    void rollback(int snap) {
        while ((int)history.size() > snap) {
            auto h = history.back();
            history.pop_back();
            if (h.parent == -1) continue;
            parent_or_size[h.parent] = h.parent_size;
            parent_or_size[h.child] = h.child_size;
            comp_sum[h.parent] = h.parent_sum;
            comp_sum[h.child] = h.child_sum;
        }
    }

    void unite(int a, int b) {
        a = root(a), b = root(b);
        if (a == b) {
            history.push_back({-1, -1, 0, 0, 0, 0});
            return;
        }
        if (parent_or_size[a] > parent_or_size[b]) swap(a, b);
        history.push_back({b, a, parent_or_size[a], parent_or_size[b], comp_sum[a], comp_sum[b]});
        parent_or_size[a] += parent_or_size[b];
        parent_or_size[b] = a;
        comp_sum[a] += comp_sum[b];
    }

    void add_value(int v, long long x) {
        int r = root(v);
        history.push_back({r, r, parent_or_size[r], parent_or_size[r], comp_sum[r], comp_sum[r]});
        comp_sum[r] += x;
    }

    long long get_sum(int v) const {
        return comp_sum[root(v)];
    }
};

int main() {
    Scanner sc;
    Printer pr;

    int n, q;
    sc.read(n, q);
    vector<long long> a(n);
    for (auto &x : a) sc.read(x);

    OfflineDynamicConnectivity dc(n, q);
    struct AddEvent {
        int v;
        long long x;
    };
    vector<vector<AddEvent>> seg_adds(2 * dc.sz);
    vector<int> type(q), query_vertex(q, -1);

    auto add_segment = [&](int l, int r, const AddEvent &event) {
        for (l += dc.sz, r += dc.sz; l < r; l >>= 1, r >>= 1) {
            if (l & 1) seg_adds[l++].push_back(event);
            if (r & 1) seg_adds[--r].push_back(event);
        }
    };

    for (int t = 0; t < q; ++t) {
        sc.read(type[t]);
        if (type[t] == 0) {
            int u, v;
            sc.read(u, v);
            dc.insert(t, u, v);
        } else if (type[t] == 1) {
            int u, v;
            sc.read(u, v);
            dc.erase(t, u, v);
        } else if (type[t] == 2) {
            int v;
            long long x;
            sc.read(v, x);
            add_segment(t, q, {v, x});
        } else {
            sc.read(query_vertex[t]);
        }
    }
    dc.build();

    RollbackUnionFindComponentSum uf(n, a);
    vector<int> snaps;
    vector<long long> ans;
    ans.reserve(q);

    dc.dfs(
        [&](int k, const vector<pair<int, int>> &edges) {
            snaps.push_back(uf.snapshot());
            for (auto &&[u, v] : edges) uf.unite(u, v);
            for (auto &&event : seg_adds[k]) uf.add_value(event.v, event.x);
        },
        [&](int, const vector<pair<int, int>> &) {
            uf.rollback(snaps.back());
            snaps.pop_back();
        },
        [&](int t) {
            if (type[t] == 3) ans.push_back(uf.get_sum(query_vertex[t]));
        }
    );

    for (auto &&x : ans) pr.println(x);
    return 0;
}
Back to top page