結果

問題 No.1054 Union add query
ユーザー kappybarkappybar
提出日時 2020-05-16 11:42:41
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 202 ms / 2,000 ms
コード長 1,720 bytes
コンパイル時間 3,771 ms
コンパイル使用メモリ 166,524 KB
実行使用メモリ 7,332 KB
最終ジャッジ日時 2023-10-22 02:49:43
合計ジャッジ時間 5,694 ms
ジャッジサーバーID
(参考情報)
judge11 / judge9
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 159 ms
4,348 KB
testcase_04 AC 202 ms
7,332 KB
testcase_05 AC 154 ms
4,348 KB
testcase_06 AC 154 ms
4,956 KB
testcase_07 AC 133 ms
4,956 KB
testcase_08 AC 146 ms
4,956 KB
testcase_09 AC 192 ms
7,332 KB
testcase_10 AC 108 ms
7,332 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
using ll = long long ;
using P = pair<int,int> ;
using pll = pair<long long,long long>;
constexpr int INF = 1e9;
constexpr long long LINF = 1e17;
constexpr int MOD = 1000000007;

 
struct Unionfind{
    vector<int> parents;
    vector<int> sum;
    int n;
    Unionfind(int n):n(n),parents(n,-1),sum(n,0){ }

    int find(int x){
        if(parents[x] < 0) return x;
        else{
            int p = find(parents[x]);
            return p;
        }
    }

    void unite(int x,int y){
        x = find(x);
        y = find(y);

        if(x==y) return;
        if(parents[x] > parents[y]) swap(x,y);
        parents[x] += parents[y];
        parents[y] = x;

        sum[y] -= sum[x];
    }  

   int size(int x){
       return -parents[find(x)];
   }

   bool same(int x,int y){
       return find(x)==find(y);
   }

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

   int count(int x){
       if(parents[x] < 0) return sum[x];
       else return sum[x] + count(parents[x]);
   }

   int get(int x){
       int res = 0;
       while(parents[x] >= 0){
           res += sum[x];
           x = parents[x];
       }
       res += sum[x];
       return res;
   }
};


int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    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 if(t==3){
            --a;
            printf("%d\n",uf.get(a));
        }
    }
    return 0;
}
0