結果

問題 No.1054 Union add query
ユーザー 🍮かんプリン🍮かんプリン
提出日時 2020-05-15 22:07:35
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 2,114 bytes
コンパイル時間 1,719 ms
コンパイル使用メモリ 169,280 KB
実行使用メモリ 14,956 KB
最終ジャッジ日時 2023-10-19 14:33:34
合計ジャッジ時間 7,420 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 WA -
testcase_02 AC 2 ms
4,348 KB
testcase_03 WA -
testcase_04 AC 702 ms
14,956 KB
testcase_05 WA -
testcase_06 AC 598 ms
7,960 KB
testcase_07 AC 542 ms
7,960 KB
testcase_08 AC 491 ms
7,960 KB
testcase_09 AC 777 ms
14,956 KB
testcase_10 AC 283 ms
14,956 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

/**
 *   @FileName	f.cpp
 *   @Author	kanpurin
 *   @Created	2020.05.15 22:07:29
**/

#include "bits/stdc++.h" 
using namespace std; 
typedef long long ll;

int n;
vector< ll > w;
// WeightedUnionFind
// verify : https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/1/DSL_1_B
template < typename T >
struct WeightedUnionFind {
private:
    vector< int > par;
    vector< int > rank;
    vector< T > diff_weight;
public:
    WeightedUnionFind(int n) {
        par.resize(n);
        rank.resize(n);
        diff_weight.resize(n);
        for (int i = 0; i < n; ++i) par[i] = i, rank[i] = 0, diff_weight[i] = 0;
    }
    int root(int x) {
        if (par[x] == x) {
            return x;
        } else {
            int r = root(par[x]);
            diff_weight[x] += diff_weight[par[x]];
            return par[x] = r;
        }
    }
    T weight(int x) {
        root(x);
        return diff_weight[x];
    }
    bool same(int x, int y) {
        return root(x) == root(y);
    }
    // y - x = w
    bool unite(int x, int y, T w) {
        w += weight(x);
        w -= weight(y);
        x = root(x);
        y = root(y);
        if (x == y) return false;
        if (rank[x] < rank[y]) swap(x, y), w = -w;
        if (rank[x] == rank[y]) ++rank[x];
        par[y] = x;
        diff_weight[y] = w;
        return true;
    }
    // y - x
    T diff(int x, int y) {
        return weight(y) - weight(x);
    }
};
int main() {
    int q;
    cin >> n >> q;
    w.resize(n, 0);
    WeightedUnionFind< ll > uf(n);
    for (int i = 0; i < q; i++) {
        int t, a, b;
        cin >> t >> a >> b;
        if (t == 1) {
            a--;
            b--;
            int ra = uf.root(a);
            int rb = uf.root(b);
            uf.unite(rb, ra, w[rb] - w[ra]);
            if (uf.root(ra) == rb) {
                w[ra] = 0;
            }
            else {
                w[rb] = 0;
            }
        } else if (t == 2) {
            a--;
            w[uf.root(a)] += b;
        } else {
            a--;
            cout << uf.diff(a,uf.root(a)) + w[uf.root(a)] << endl;
        }
    }
    return 0;
}
0