結果

問題 No.1054 Union add query
ユーザー wkwk
提出日時 2020-05-16 13:56:22
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,993 bytes
コンパイル時間 2,071 ms
コンパイル使用メモリ 172,508 KB
実行使用メモリ 9,164 KB
最終ジャッジ日時 2023-10-22 06:25:34
合計ジャッジ時間 7,769 ms
ジャッジサーバーID
(参考情報)
judge13 / judge9
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 WA -
testcase_02 AC 2 ms
4,348 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 AC 572 ms
5,732 KB
testcase_07 AC 531 ms
5,732 KB
testcase_08 AC 476 ms
5,732 KB
testcase_09 AC 742 ms
9,164 KB
testcase_10 AC 280 ms
9,164 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 par[x] = 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);
            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.root(first)) break;
                first = uf.par[first];
            }
            cout << sum << endl;
        }
    }
    return 0;
}

0