結果

問題 No.1054 Union add query
コンテスト
ユーザー mot
提出日時 2020-05-15 22:17:53
言語 C++11
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=gnu++11 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 92 ms / 2,000 ms
コード長 1,788 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 510 ms
コンパイル使用メモリ 106,624 KB
実行使用メモリ 15,676 KB
最終ジャッジ日時 2026-04-07 21:28:25
合計ジャッジ時間 2,210 ms
ジャッジサーバーID
(参考情報)
judge3_1 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 8
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
#include<vector>
#include<list>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
#define fi first
#define se second
#define mp make_pair
#define rep(i, n) for(int i=0;i<n;++i)
#define rrep(i, n) for(int i=n;i>=0;--i)
const int inf=1e9+7;
const ll mod=1e9+7;
const ll big=1e18;
const double PI=3.14159265359;

int par[500005], siz[500005], num[500005];

int root(int x){
    while(x!=par[x]) x = par[x];
    return x;
}

int main() {
    int N, Q;
    scanf("%d %d", &N, &Q);
    int T[Q], A[Q], B[Q];
    for(int i=0;i<Q;++i){
        scanf("%d %d %d", &T[i], &A[i], &B[i]);
        A[i]--;
        if(T[i]==1){
            B[i]--;
        }
    }

    for(int i=0;i<N;++i){
        par[i] = i;
        siz[i] = 1;
        num[i] = 0;
    }

    int roota, rootb;
    int tmp, x;
    for(int i=0;i<Q;++i){
        if(T[i]==1){
            roota = root(A[i]);
            rootb = root(B[i]);
            if(roota != rootb){
                if(siz[roota] > siz[rootb]) swap(roota, rootb);
                num[roota] -= num[rootb];
                par[roota] = rootb;
                siz[rootb] += siz[roota];
            }
        }
        if(T[i]==2){
            roota = root(A[i]);
            num[roota] += B[i];
            /**
            for(int j=0;j<N;++j){
                if(roota == root(j)){
                    num[j] += B[i];
                }
            }
            **/
        }
        if(T[i]==3){
            x = A[i];
            tmp = 0;
            while(x!=par[x]){
                tmp += num[x];
                x = par[x];
            }
            tmp += num[x];
            printf("%d\n", tmp);
        }
    }
}

0