結果

問題 No.1054 Union add query
ユーザー merom686merom686
提出日時 2020-05-16 02:52:33
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 185 ms / 2,000 ms
コード長 1,237 bytes
コンパイル時間 947 ms
コンパイル使用メモリ 88,748 KB
実行使用メモリ 7,128 KB
最終ジャッジ日時 2023-10-19 23:04:21
合計ジャッジ時間 3,634 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 AC 2 ms
4,348 KB
testcase_02 AC 2 ms
4,348 KB
testcase_03 AC 144 ms
4,348 KB
testcase_04 AC 185 ms
7,128 KB
testcase_05 AC 139 ms
4,368 KB
testcase_06 AC 141 ms
4,752 KB
testcase_07 AC 120 ms
4,752 KB
testcase_08 AC 139 ms
4,752 KB
testcase_09 AC 177 ms
7,128 KB
testcase_10 AC 100 ms
7,128 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
using ll = long long;

struct UnionFind {
    UnionFind(int n) : p(n, -1), s(n, 0) {}
    int root(int u) {
        return p[u] < 0 ? u : root(p[u]);
    }
    int size(int u) {
        return -p[root(u)];
    }
    bool same(int u, int v) {
        return root(u) == root(v);
    }
    void unite(int u, int v) {
        u = root(u);
        v = root(v);
        if (u == v) return;
        if (p[u] > p[v]) swap(u, v);
        p[u] += p[v];
        p[v] = u;
        s[v] -= s[u];
    }
    void add(int u, int a) {
        s[root(u)] += a;
    }
    int sum(int u) {
        return p[u] < 0 ? s[u] : s[u] + sum(p[u]);
    }
    vector<int> p, s;
};

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

    int n, q;
    cin >> n >> q;

    UnionFind uf(n);

    while (q--) {
        int t, a, b;
        cin >> t >> a >> b;
        a--;

        if (t == 1) {
            b--;
            if (!uf.same(a, b)) uf.unite(a, b);

        } else if (t == 2) {
            uf.add(a, b);

        } else {
            cout << uf.sum(a) << '\n';
        }
    }

    return 0;
}
0