結果

問題 No.1054 Union add query
ユーザー hedwig100hedwig100
提出日時 2020-05-16 10:44:49
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 199 ms / 2,000 ms
コード長 2,205 bytes
コンパイル時間 1,662 ms
コンパイル使用メモリ 170,624 KB
実行使用メモリ 7,212 KB
最終ジャッジ日時 2023-10-22 01:16:37
合計ジャッジ時間 4,480 ms
ジャッジサーバーID
(参考情報)
judge14 / judge10
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 158 ms
4,348 KB
testcase_04 AC 199 ms
7,212 KB
testcase_05 AC 153 ms
4,348 KB
testcase_06 AC 153 ms
4,836 KB
testcase_07 AC 134 ms
4,836 KB
testcase_08 AC 145 ms
4,836 KB
testcase_09 AC 190 ms
7,212 KB
testcase_10 AC 108 ms
7,212 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); i ++)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PL;
typedef pair<int,int> P;
const int INF = 1e9;
const int MOD = 17;
const vector<int> dy = {-1,0,1,0};
const vector<int> dx = {0,1,0,-1};

struct UnionFind {
    int N;
    vector<int> parents;
    vector<int> count;

    UnionFind(int _N) : N(_N){
        parents = vector<int>(N,-1);
        count = vector<int>(N,0);
    }

    int find(int x) { //xの親を返す
        if (parents[x] < 0) return x;
        else {
            int p = find(parents[x]);
            return p;
        }
    }
    
    void unite(int x, int y) {  //xとyの含むグループを併合
        int px = find(x);
        int py = find(y);

        if (parents[px] > parents[py]) swap(px,py); 
        if (px != py) {
            parents[px] += parents[py];
            count[py] -= count[px]; 
            parents[py] = px;
        }     
    }

    bool same(int x, int y) { //x,yが同じグループにいるか判定
        return find(x) == find(y);
    }

    int size(int x) { //xと同じグループのメンバーの個数
        return parents[find(x)];
    }
    
    vector<int> root() {//ufの根を列挙
        vector<int> res;
        for (int i = 0; i < N; i ++) {
            if (parents[i] < 0) res.push_back(i);
        }
        return res;
    }

    int group_count() { //ufのグループの数を数える
        int cnt = 0;
        for (int i = 0; i < N; i ++) {
            if (parents[i] < 0) cnt ++;
        }
        return cnt;
    }

    void add(int x,int a) {
        int p = find(x);
        count[p] += a;
    }

    int calc(int x) {
        if (parents[x] < 0) return count[x];
        int ans = calc(parents[x]);
        return ans + count[x];
    }

};

int main() {
    int N,Q; scanf("%d %d",&N,&Q);
    UnionFind uf(N);
    rep(i,Q) {
        int t,a,b; scanf("%d %d %d",&t,&a,&b);
        if (t == 1) {
            a --; b--;
            uf.unite(a,b);
        }
        else if (t == 2) {
            a --;
            uf.add(a,b);
        }
        else {
            a --;
            printf("%d\n",uf.calc(a));
        }
    }
}
0