結果

問題 No.1054 Union add query
ユーザー ShibuyapShibuyap
提出日時 2020-05-15 23:37:17
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 723 ms / 2,000 ms
コード長 1,748 bytes
コンパイル時間 2,037 ms
コンパイル使用メモリ 205,100 KB
実行使用メモリ 18,128 KB
最終ジャッジ日時 2023-10-19 17:41:58
合計ジャッジ時間 7,726 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
12,456 KB
testcase_01 AC 4 ms
12,460 KB
testcase_02 AC 4 ms
12,456 KB
testcase_03 AC 582 ms
16,940 KB
testcase_04 AC 656 ms
18,128 KB
testcase_05 AC 569 ms
14,612 KB
testcase_06 AC 558 ms
15,784 KB
testcase_07 AC 523 ms
15,784 KB
testcase_08 AC 465 ms
14,736 KB
testcase_09 AC 723 ms
18,128 KB
testcase_10 AC 278 ms
12,456 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
using namespace std;
typedef long long int ll;
typedef pair<int,int> P;
#define yn {puts("Yes");}else{puts("No");}

const int MAX_N = 1000100;
int par_[MAX_N]; // 親
int rank_[MAX_N]; // 木の深さ
ll val[MAX_N];

// n要素で初期化
void UFinit(){
    for(int i=0;i<MAX_N;i++){
        par_[i] = i;
        rank_[i] = 0;
    }
}

// 木の根を求める
int find_(int x){
    if(par_[x] == x){
        return x;
    }else{
        return find_(par_[x]);
    }
}

// xとyの属する集合を併合
void unite(int x, int y){
    x = find_(x);
    y = find_(y);
    if(x == y) return;

    if(rank_[x] < rank_[y]){
        val[x] -= val[y];
        par_[x] = y;
    }else{
        val[y] -= val[x];
        par_[y] = x;
        if(rank_[x] == rank_[y]) rank_[x]++;
    }
}

// xとyが同じ集合に属するか否か
bool same(int x, int y){
    return find_(x) == find_(y);
}

ll calc(int x){
    ll res = val[x];
    
    if(par_[x] == x){
        return res;
    }

    res += calc(par_[x]);

    return res;
}


int main() {
    /*
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    */
    UFinit();

    int n, q;
    cin >> n >> q;
    vector<ll> ans;
    rep(i,q){
        int t, a, b;
        cin >> t >> a >> b;
        if(t == 1){
            if(same(a,b))continue;
            unite(a,b);
        }else if(t == 2){
            int x = find_(a);
            val[x] += b;
        }else if(t == 3){
            ans.push_back(calc(a));
        }
    }

    rep(i,ans.size()) cout << ans[i] << endl;

    if(ans.size() == 0) cout << endl;

    return 0;
}

0