結果

問題 No.1054 Union add query
ユーザー niuezniuez
提出日時 2020-05-15 22:00:51
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 167 ms / 2,000 ms
コード長 2,163 bytes
コンパイル時間 1,618 ms
コンパイル使用メモリ 170,608 KB
実行使用メモリ 15,052 KB
最終ジャッジ日時 2023-10-19 14:18:41
合計ジャッジ時間 4,445 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 142 ms
5,556 KB
testcase_04 AC 167 ms
15,052 KB
testcase_05 AC 135 ms
4,500 KB
testcase_06 AC 143 ms
7,932 KB
testcase_07 AC 125 ms
7,932 KB
testcase_08 AC 137 ms
7,932 KB
testcase_09 AC 159 ms
15,052 KB
testcase_10 AC 102 ms
15,052 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <vector>
#include <tuple>
#include <iostream>
using std::cout;
using std::endl;
using i64 = long long;

struct union_find {
  std::vector<int> par;
  std::vector<i64> Sigma;
  union_find(int N): par(N * 2, -1) , Sigma(N * 2, 0) {
  }
  int root(int x) {
    if(par[x] < 0) {
      return x;
    }
    int v = x;
    while(par[par[v]] >= 0) {
      v = par[v];
      Sigma[x] += Sigma[v];
    }
    par[x] = par[v];
    return par[v];
  }
  std::tuple<int, int> unite(int x, int y) {
    x = root(x);
    y = root(y);
    if(x == y) return { -1, -1 };
    if(par[x] > par[y]) std::swap(x, y);
    par[x] += par[y];
    par[y] = x;
    Sigma[y] -= Sigma[x];
    return { x, y };
  }
  void add(int v, i64 a) {
    Sigma[root(v)] += a;
  }
  i64 value(int v) {
    int r = root(v);
    if(r == v) {
      return Sigma[v];
    }
    else {
      return Sigma[v] + Sigma[r];
    } 
  }
};

#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define rep(i,s,e) for(i64 (i) = (s);(i) < (e);(i)++)
#define all(x) x.begin(),x.end()

template<class T>
static inline std::vector<T> ndvec(size_t&& n, T val) noexcept {
  return std::vector<T>(n, std::forward<T>(val));
}

template<class... Tail>
static inline auto ndvec(size_t&& n, Tail&&... tail) noexcept {
  return std::vector<decltype(ndvec(std::forward<Tail>(tail)...))>(n, ndvec(std::forward<Tail>(tail)...));
}

template<class T, class Cond>
struct chain {
  Cond cond; chain(Cond cond) : cond(cond) {}
  bool operator()(T& a, const T& b) const {
    if(cond(a, b)) { a = b; return true; }
    return false;
  }
};
template<class T, class Cond>
chain<T, Cond> make_chain(Cond cond) { return chain<T, Cond>(cond); }

int main() {
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
  int N, Q;
  cin >> N >> Q;
  union_find uf(N);
  while(Q--) {
    int t, a, b;
    cin >> t >> a >> b;
    a--;
    if(t == 1) {
      b--;
      uf.unite(a, b);
    }
    else if(t == 2) {
      uf.add(a, b);
    }
    else {
      cout << uf.value(a) << "\n";
    }
    /*
    cout << Q << endl;
    rep(i,0,N) {
      cout << i << " = " << uf.Sigma[i] << " " << uf.par[i] << endl;
    }*/
  }
}
0