結果

問題 No.1054 Union add query
ユーザー rokahikou1rokahikou1
提出日時 2020-10-05 15:03:01
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 494 ms / 2,000 ms
コード長 2,160 bytes
コンパイル時間 862 ms
コンパイル使用メモリ 99,900 KB
実行使用メモリ 33,408 KB
最終ジャッジ日時 2023-09-27 03:09:43
合計ジャッジ時間 6,217 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 360 ms
10,152 KB
testcase_04 AC 440 ms
33,408 KB
testcase_05 AC 330 ms
6,616 KB
testcase_06 AC 319 ms
15,048 KB
testcase_07 AC 309 ms
15,052 KB
testcase_08 AC 225 ms
14,944 KB
testcase_09 AC 494 ms
30,460 KB
testcase_10 AC 97 ms
30,488 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define rep(i, n) for(int(i) = 0; (i) < (n); (i)++)
#define FOR(i, m, n) for(int(i) = (m); (i) < (n); (i)++)
#define All(v) (v).begin(), (v).end()
#define pb push_back
#define MP(a, b) make_pair((a), (b))
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const int INF = 1 << 30;
const ll LINF = 1LL << 60;
const int MOD = 1e9 + 7;

// UnionFind
struct UnionFind {
    vector<ll> par;
    vector<ll> siz;
    vector<ll> add;
    vector<ll> rest;
    vector<vector<int>> childs;

    UnionFind(ll N) : par(N), siz(N, 1LL), add(N), rest(N), childs(N) {
        for(int i = 0; i < N; i++)
            par[i] = i;
    }
    int root(int x) {
        if(par[x] == x)
            return x;
        return par[x] = root(par[x]);
    }
    void unite(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        if(rx == ry)
            return;
        if(siz[rx] < siz[ry])
            swap(rx, ry);
        siz[rx] += siz[ry];
        par[ry] = rx;
        ll dif = add[ry] - add[rx];
        rest[ry] += dif;
        childs[rx].pb(ry);
        for(auto c : childs[ry]) {
            rest[c] += dif;
            childs[rx].pb(c);
        }
        childs[ry].clear();
    }
    bool same(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        return rx == ry;
    }

    void addQ(int x, int num) { add[root(x)] += num; }

    int response(int x) { return add[root(x)] + rest[x]; }

    ll size(ll x) { return siz[root(x)]; }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N, Q;
    cin >> N >> Q;
    UnionFind uf(N);
    rep(i, Q) {
        int T, A, B;
        cin >> T >> A >> B;
        if(T == 1) {
            A--, B--;
            uf.unite(A, B);
        } else if(T == 2) {
            A--;
            uf.addQ(A, B);
        } else {
            A--;
            cout << uf.response(A) << endl;
        }
    }
    return 0;
}
0