結果

問題 No.1054 Union add query
ユーザー merom686merom686
提出日時 2020-05-16 02:52:33
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 210 ms / 2,000 ms
コード長 1,237 bytes
コンパイル時間 1,184 ms
コンパイル使用メモリ 92,412 KB
最終ジャッジ日時 2025-01-10 12:18:13
ジャッジサーバーID
(参考情報)
judge2 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 8
権限があれば一括ダウンロードができます

ソースコード

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