結果

問題 No.1054 Union add query
ユーザー tonegawatonegawa
提出日時 2020-08-12 00:01:21
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 150 ms / 2,000 ms
コード長 1,786 bytes
コンパイル時間 1,071 ms
コンパイル使用メモリ 119,616 KB
実行使用メモリ 11,136 KB
最終ジャッジ日時 2024-04-17 17:55:49
合計ジャッジ時間 3,529 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 2 ms
6,944 KB
testcase_02 AC 1 ms
6,940 KB
testcase_03 AC 140 ms
6,940 KB
testcase_04 AC 150 ms
11,136 KB
testcase_05 AC 133 ms
6,940 KB
testcase_06 AC 124 ms
6,940 KB
testcase_07 AC 116 ms
6,940 KB
testcase_08 AC 119 ms
6,944 KB
testcase_09 AC 138 ms
11,136 KB
testcase_10 AC 96 ms
11,136 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <algorithm>
#include <set>
#include <map>
#include <bitset>
#include <cmath>
#include <functional>
#include <iomanip>
#define vll vector<ll>
#define vvvl vector<vvl>
#define vvl vector<vector<ll>>
#define VV(a, b, c, d) vector<vector<d>>(a, vector<d>(b, c))
#define VVV(a, b, c, d) vector<vvl>(a, vvl(b, vll (c, d)));
#define re(c, b) for(ll c=0;c<b;c++)
#define all(obj) (obj).begin(), (obj).end()
typedef long long int ll;
typedef long double ld;
using namespace std;

struct UF{
  std::vector<int> par, dep, sz, dat;
  UF(int n){
    par.resize(n+1), dep.resize(n+1), sz.resize(n+1), dat.resize(n+1);
    init(n);
  }
  void init(int nu) {
    for(int iu=0;iu<=nu;iu++){
      par[iu] = iu;
      dep[iu] = 0;
      sz[iu] = 1;
      dat[iu] = 0;
    }
  }

  int find(int xu){
    if(par[xu] == xu) return xu;
    return find(par[xu]);
  }

  ll get(int xu){
    if(par[xu]==xu) return dat[xu];
    return dat[xu] + get(par[xu]);
  }

  void unite(int xu, int yu){
    xu=find(xu);
    yu=find(yu);
    if(xu == yu) return;
    if(dep[xu] < dep[yu]){
      sz[yu] += sz[xu];
      par[xu] = yu;
      dat[xu] -= dat[yu];
    }else{
      par[yu] = xu;
      sz[xu] += sz[yu];
      dat[yu] -= dat[xu];
      if(dep[xu] == dep[yu]) dep[xu]++;
    }
  }
  bool same(int xu, int yu){ return find(xu) == find(yu);}
  int get_size(int x){return sz[find(x)];}
};

int main(int argc, char const *argv[]) {
  ll n, q;scanf("%lld %lld", &n, &q);
  UF uf(n+1);
  for(int i=0;i<q;i++){
    ll a, b, c;scanf("%lld %lld %lld", &a, &b, &c);
    if(a==1) uf.unite(b, c);
    if(a==2){
      ll p = uf.find(b);
      uf.dat[p] += c;
    }
    if(a==3) printf("%lld\n", uf.get(b));
  }
  return 0;
}
0