MX Notes · Templates

Compact C++17 snippet archive for ICPC regional practice and problem reviews.

Disjoint Set Union with Rollback

2026-11-28DSUOffline

Omit path compression and unite by size so every merge mutates only two entries. Recording modified pairs on a stack enables O(log n) queries with divide-and-conquer on time.

struct RollbackDSU {
    vector<int> p, sz;
    vector<pair<int,int>> hist;
    RollbackDSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }
    int find(int x) const { return p[x] == x ? x : find(p[x]); }
    bool unite(int a, int b) {
        a = find(a); b = find(b);
        if (a == b) return false;
        if (sz[a] < sz[b]) swap(a, b);
        hist.push_back({b, sz[a]});
        p[b] = a; sz[a] += sz[b];
        return true;
    }
    void rollback(int snap) {
        while ((int)hist.size() > snap) {
            auto [b, old] = hist.back(); hist.pop_back();
            int a = p[b]; sz[a] = old; p[b] = b;
        }
    }
};

Tarjan Strongly Connected Components

2026-11-12GraphsSCC

Track discovery time dfn[u] and lowest reachable ancestor low[u]. Components are popped in reverse topological order, making condensation DAG dynamic programming immediate without an extra sort.

Suffix Automaton Construction Notes

2026-10-30StringsSAM

A string of length n creates at most 2n - 1 states and 3n - 4 transitions. Pre-allocate 2 * n + 5 nodes to avoid vector reallocations in tight memory limits.