結果
問題 |
No.1054 Union add query
|
ユーザー |
![]() |
提出日時 | 2020-10-05 15:03:01 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 535 ms / 2,000 ms |
コード長 | 2,160 bytes |
コンパイル時間 | 1,122 ms |
コンパイル使用メモリ | 101,120 KB |
実行使用メモリ | 33,664 KB |
最終ジャッジ日時 | 2024-07-19 20:32:38 |
合計ジャッジ時間 | 6,612 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 8 |
ソースコード
#include <algorithm> #include <cmath> #include <cstdint> #include <cstdio> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define rep(i, n) for(int(i) = 0; (i) < (n); (i)++) #define FOR(i, m, n) for(int(i) = (m); (i) < (n); (i)++) #define All(v) (v).begin(), (v).end() #define pb push_back #define MP(a, b) make_pair((a), (b)) using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; const int INF = 1 << 30; const ll LINF = 1LL << 60; const int MOD = 1e9 + 7; // UnionFind struct UnionFind { vector<ll> par; vector<ll> siz; vector<ll> add; vector<ll> rest; vector<vector<int>> childs; UnionFind(ll N) : par(N), siz(N, 1LL), add(N), rest(N), childs(N) { for(int i = 0; i < N; i++) par[i] = i; } int root(int x) { if(par[x] == x) return x; return par[x] = root(par[x]); } void unite(int x, int y) { int rx = root(x); int ry = root(y); if(rx == ry) return; if(siz[rx] < siz[ry]) swap(rx, ry); siz[rx] += siz[ry]; par[ry] = rx; ll dif = add[ry] - add[rx]; rest[ry] += dif; childs[rx].pb(ry); for(auto c : childs[ry]) { rest[c] += dif; childs[rx].pb(c); } childs[ry].clear(); } bool same(int x, int y) { int rx = root(x); int ry = root(y); return rx == ry; } void addQ(int x, int num) { add[root(x)] += num; } int response(int x) { return add[root(x)] + rest[x]; } ll size(ll x) { return siz[root(x)]; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; UnionFind uf(N); rep(i, Q) { int T, A, B; cin >> T >> A >> B; if(T == 1) { A--, B--; uf.unite(A, B); } else if(T == 2) { A--; uf.addQ(A, B); } else { A--; cout << uf.response(A) << endl; } } return 0; }