結果

問題 No.1054 Union add query
ユーザー milanis48663220milanis48663220
提出日時 2020-06-20 01:53:46
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 159 ms / 2,000 ms
コード長 1,251 bytes
コンパイル時間 607 ms
コンパイル使用メモリ 82,244 KB
実行使用メモリ 9,360 KB
最終ジャッジ日時 2023-09-16 16:34:30
合計ジャッジ時間 3,143 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,556 KB
testcase_01 AC 2 ms
5,592 KB
testcase_02 AC 2 ms
5,620 KB
testcase_03 AC 149 ms
6,372 KB
testcase_04 AC 159 ms
9,360 KB
testcase_05 AC 142 ms
5,880 KB
testcase_06 AC 138 ms
7,076 KB
testcase_07 AC 128 ms
7,116 KB
testcase_08 AC 133 ms
7,280 KB
testcase_09 AC 155 ms
9,308 KB
testcase_10 AC 97 ms
7,364 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <queue>
#include <set>
#include <map>

using namespace std;
typedef long long ll;

int N, Q;
int par[500000];
int sz[500000];
int dat[500000];

int cnt;
int root(int v){
    return par[v] == v ? v : root(par[v]);
}

int calc(int v){
    int ans = dat[v];
    while(v != par[v]){
        cnt++;
        v = par[v]; ans += dat[v];
    }
    return ans;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout << setprecision(10) << fixed;
    scanf("%d %d", &N, &Q);
    for(int i = 0; i < N; i++){
        par[i] = i;
        sz[i] = 1;
    }
    for(int i = 0; i < Q; i++){
        cnt = 0;
        int t, a, b;
        scanf("%d %d %d", &t, &a, &b);
        if(t == 1){
            a--; b--;
            int ra = root(a), rb = root(b);
            if(ra != rb){
                if(sz[ra] > sz[rb]) swap(ra, rb);
                par[ra] = rb;
                dat[ra] -= dat[rb];
                sz[rb] = max(sz[rb], sz[ra]+1); 
            }
        }else if(t == 2) {
            a--;
            int r = root(a);
            dat[r] += b;
        }else{
            a--;
            cnt = 0;
            printf("%d\n", calc(a));
        }
    }
}
0