結果

問題 No.1054 Union add query
ユーザー MisterMister
提出日時 2020-08-04 04:24:12
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 195 ms / 2,000 ms
コード長 1,739 bytes
コンパイル時間 750 ms
コンパイル使用メモリ 76,252 KB
実行使用メモリ 10,892 KB
最終ジャッジ日時 2023-10-11 23:52:39
合計ジャッジ時間 4,879 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,352 KB
testcase_01 AC 2 ms
4,352 KB
testcase_02 AC 1 ms
4,352 KB
testcase_03 AC 148 ms
4,536 KB
testcase_04 AC 195 ms
10,784 KB
testcase_05 AC 139 ms
4,368 KB
testcase_06 AC 135 ms
6,264 KB
testcase_07 AC 118 ms
6,100 KB
testcase_08 AC 132 ms
6,264 KB
testcase_09 AC 174 ms
10,824 KB
testcase_10 AC 97 ms
10,892 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <numeric>
#include <vector>

using lint = long long;

struct UnionFind {
    std::vector<int> par, sz;
    std::vector<lint> xs;

    explicit UnionFind(int n)
        : par(n), sz(n, 1), xs(n, 0) {
        std::iota(par.begin(), par.end(), 0);
    }

    int find(int v) {
        while (par[v] != v) v = par[v];
        return v;
    }

    void add(int v, lint x) {
        v = find(v);
        xs[v] += x;
    }

    lint get(int v) {
        lint ret = xs[v];
        while (par[v] != v) {
            v = par[v];
            ret += xs[v];
        }
        return ret;
    }

    void unite(int u, int v) {
        u = find(u), v = find(v);
        if (u == v) return;

        if (sz[u] < sz[v]) std::swap(u, v);
        sz[u] += sz[v];
        xs[v] -= xs[u];
        par[v] = u;
    }

    bool same(int u, int v) { return find(u) == find(v); }
    bool ispar(int v) { return v == find(v); }
    int size(int v) { return sz[find(v)]; }
};

void solve() {
    int n, q;
    std::cin >> n >> q;

    UnionFind uf(n);
    while (q--) {
        int t;
        std::cin >> t;

        switch (t) {
            case 1: {
                int u, v;
                std::cin >> u >> v;
                uf.unite(--u, --v);
                break;
            }
            case 2: {
                int v;
                lint x;
                std::cin >> v >> x;
                uf.add(--v, x);
                break;
            }
            default: {
                int v, b;
                std::cin >> v >> b;
                std::cout << uf.get(--v) << "\n";
            }
        }
    }
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    solve();

    return 0;
}
0