結果
問題 | No.1054 Union add query |
ユーザー |
|
提出日時 | 2020-08-04 04:24:12 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 306 ms / 2,000 ms |
コード長 | 1,739 bytes |
コンパイル時間 | 1,134 ms |
コンパイル使用メモリ | 75,100 KB |
最終ジャッジ日時 | 2025-01-12 14:12:09 |
ジャッジサーバーID (参考情報) |
judge3 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 8 |
ソースコード
#include <iostream> #include <numeric> #include <vector> using lint = long long; struct UnionFind { std::vector<int> par, sz; std::vector<lint> xs; explicit UnionFind(int n) : par(n), sz(n, 1), xs(n, 0) { std::iota(par.begin(), par.end(), 0); } int find(int v) { while (par[v] != v) v = par[v]; return v; } void add(int v, lint x) { v = find(v); xs[v] += x; } lint get(int v) { lint ret = xs[v]; while (par[v] != v) { v = par[v]; ret += xs[v]; } return ret; } void unite(int u, int v) { u = find(u), v = find(v); if (u == v) return; if (sz[u] < sz[v]) std::swap(u, v); sz[u] += sz[v]; xs[v] -= xs[u]; par[v] = u; } bool same(int u, int v) { return find(u) == find(v); } bool ispar(int v) { return v == find(v); } int size(int v) { return sz[find(v)]; } }; void solve() { int n, q; std::cin >> n >> q; UnionFind uf(n); while (q--) { int t; std::cin >> t; switch (t) { case 1: { int u, v; std::cin >> u >> v; uf.unite(--u, --v); break; } case 2: { int v; lint x; std::cin >> v >> x; uf.add(--v, x); break; } default: { int v, b; std::cin >> v >> b; std::cout << uf.get(--v) << "\n"; } } } } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }