結果

問題 No.1054 Union add query
ユーザー IKyoproIKyopro
提出日時 2020-05-15 22:47:06
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 304 ms / 2,000 ms
コード長 1,407 bytes
コンパイル時間 2,147 ms
コンパイル使用メモリ 208,192 KB
実行使用メモリ 37,256 KB
最終ジャッジ日時 2023-10-19 15:53:15
合計ジャッジ時間 4,935 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 175 ms
10,988 KB
testcase_04 AC 304 ms
37,256 KB
testcase_05 AC 149 ms
7,276 KB
testcase_06 AC 160 ms
17,572 KB
testcase_07 AC 143 ms
17,572 KB
testcase_08 AC 158 ms
17,572 KB
testcase_09 AC 226 ms
36,404 KB
testcase_10 AC 140 ms
36,404 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <class T, class U> using Pa = pair<T, U>;
template <class T> using vec = vector<T>;
template <class T> using vvec = vector<vec<T>>;

class QuickFind{
private:
    vec<int> G;
    vec<int> val;
    vvec<int> comp;
public:
    QuickFind(int N){
        G.resize(N);
        comp.resize(N);
        val.resize(N);
        iota(G.begin(),G.end(),0);
        for(int i=0;i<N;i++) comp[i].push_back(i);
    }

    void unite(int x,int y){
        x = G[x],y = G[y];
        if(is_same_set(x,y)) return ;
        if(comp[x].size()<comp[y].size()) swap(x,y);
        int v = val[y];
        for(auto& e:comp[y]){
            comp[x].push_back(e);
            G[e] = x;
            val[e] -= val[x];
            if(e!=y) val[e] += v;
        }
        comp[y].clear();
    }
    bool is_same_set(int x,int y){return G[x]==G[y];}
    int getval(int x){return val[x]+val[G[x]]*(G[x]!=x);}
    int addval(int x,int v){return val[G[x]] += v;}
};

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N,Q;
    cin >> N >> Q;
    QuickFind uf(N);
    vec<int> now(N);
    while(Q--){
        int t,a,b;
        cin >> t >> a >> b;
        a--;
        if(t==1){
            b--;
            uf.unite(a,b);
        }
        if(t==2) uf.addval(a,b);
        if(t==3){
            cout << uf.getval(a) << "\n";
        }
    }   
}
0