結果

問題 No.1054 Union add query
ユーザー wkwk
提出日時 2020-05-16 14:16:18
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 736 ms / 2,000 ms
コード長 2,049 bytes
コンパイル時間 2,370 ms
コンパイル使用メモリ 170,988 KB
実行使用メモリ 9,148 KB
最終ジャッジ日時 2023-10-22 06:50:15
合計ジャッジ時間 7,775 ms
ジャッジサーバーID
(参考情報)
judge14 / 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 590 ms
4,660 KB
testcase_04 AC 663 ms
9,148 KB
testcase_05 AC 574 ms
4,348 KB
testcase_06 AC 568 ms
5,716 KB
testcase_07 AC 529 ms
5,716 KB
testcase_08 AC 473 ms
5,716 KB
testcase_09 AC 736 ms
9,148 KB
testcase_10 AC 278 ms
9,148 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; (i) < (n); (i)++)
using namespace std;

long modpow(long a, long n, long mod) {
    long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

// a^{-1} mod を計算する
long modinv(long a, long mod) {
    return modpow(a, mod - 2, mod);
}

int GCD(int a, int b){
    if(b == 0) return a; 
    if(a < b) return GCD(b, a);
    else return GCD(b, a%b);
}


struct UnionFind {
    vector<int> par;
    vector<int> rank;

    UnionFind(int n = 1){
        init(n);
    }

    void init(int n = 1){
        par.resize(n);
        rank.resize(n);
        REP(i, n) par[i] = i, rank[i] = 0; 
    }

    int root(int x){
        if(par[x] == x) return x;
        else return root(par[x]);
    }

    bool issame(int x, int y){
        return root(x) == root(y);
    }

    void merge(int x, int y){
        x = root(x); y = root(y);
        if(x == y) return;
        if(rank[x] < rank[y]) swap(x, y);
        if(rank[x] == rank[y]) rank[x]++;
        par[y] = x;
        return;
    }
};

int main()
{   
    int N, Q; cin >> N >> Q;
    UnionFind uf(N);
    int num[500005];
    REP(i, N) num[i] = 0;
    REP(i, Q){
        //REP(i, N) cout << num[i] << " ";
        //cout << endl;
        int T, A, B; cin >> T >> A >> B;
        if(T==1){
            int nea = uf.root(A-1);
            int neb = uf.root(B-1);
            if(nea != neb){
                uf.merge(A-1, B-1);
                if(uf.root(A-1) == nea){
                    num[neb] -= num[nea];
                }else{
                    num[nea] -= num[neb];
                }
            }
        }else if(T==2){
            num[uf.root(A-1)] += B;
        }else{
            int sum = 0;
            int first = A-1;
            for(;;){
                sum += num[first];
                if(first == uf.par[first]) break;
                first = uf.par[first];
            }
            cout << sum << endl;
        }
    }
    return 0;
}

0