結果

問題 No.1054 Union add query
ユーザー beetbeet
提出日時 2020-05-15 21:32:37
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 208 ms / 2,000 ms
コード長 1,629 bytes
コンパイル時間 2,239 ms
コンパイル使用メモリ 206,424 KB
実行使用メモリ 11,144 KB
最終ジャッジ日時 2023-10-19 12:44:06
合計ジャッジ時間 6,494 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 145 ms
4,808 KB
testcase_04 AC 208 ms
11,144 KB
testcase_05 AC 134 ms
4,348 KB
testcase_06 AC 141 ms
6,392 KB
testcase_07 AC 124 ms
6,392 KB
testcase_08 AC 141 ms
6,392 KB
testcase_09 AC 185 ms
11,144 KB
testcase_10 AC 103 ms
11,144 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
using Int = long long;
const char newl = '\n';


template <typename T>
struct WeightedUnionFind{
  vector<int> rs,ps;
  vector<T> ws;

  WeightedUnionFind(){}
  WeightedUnionFind(int n):
    rs(n,1),ps(n),ws(n,T(0)){iota(ps.begin(),ps.end(),0);}

  int find(int x){
    if(x==ps[x]) return x;
    int t=find(ps[x]);
    ws[x]+=ws[ps[x]];
    return ps[x]=t;
  }

  T weight(int x){
    find(x);
    return ws[x];
  }

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

  void unite(int x,int y,T w){
    w+=weight(x);
    w-=weight(y);
    x=find(x);y=find(y);
    if(x==y) return;
    if(rs[x]<rs[y]) swap(x,y),w=-w;
    rs[x]+=rs[y];
    ps[y]=x;
    ws[y]=w;
  }

  T diff(int x,int y){
    return weight(y)-weight(x);
  }
};

//INSERT ABOVE HERE
signed main(){
  cin.tie(0);
  ios::sync_with_stdio(0);

  int n,q;
  cin>>n>>q;
  WeightedUnionFind<int> uf(n);

  vector<int> vs(n,0);
  auto add=[&](int a,int b){
    vs[uf.find(a)]+=b;
  };
  auto query=[&](int a){
    int r=uf.find(a);
    return uf.diff(a,r)+vs[r];
  };
  auto unite=[&](int a,int b){
    a=uf.find(a);
    b=uf.find(b);
    if(a==b) return;
    int x=query(a);
    int y=query(b);
    uf.unite(a,b,x-y);
  };

  for(int i=0;i<q;i++){
    int t,a,b;
    cin>>t>>a>>b;
    if(t==1){
      a--;b--;
      unite(a,b);
    }
    if(t==2){
      a--;
      add(a,b);
    }
    if(t==3){
      a--;
      cout<<query(a)<<newl;
    }
  }
  return 0;
}
0