結果
問題 | No.1054 Union add query |
ユーザー | rodea |
提出日時 | 2020-05-29 16:01:59 |
言語 | C++14 (gcc 12.3.0 + boost 1.83.0) |
結果 |
AC
|
実行時間 | 530 ms / 2,000 ms |
コード長 | 2,686 bytes |
コンパイル時間 | 1,330 ms |
コンパイル使用メモリ | 116,508 KB |
実行使用メモリ | 38,960 KB |
最終ジャッジ日時 | 2024-10-15 04:47:19 |
合計ジャッジ時間 | 6,400 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 2 ms
6,820 KB |
testcase_01 | AC | 2 ms
6,824 KB |
testcase_02 | AC | 1 ms
6,816 KB |
testcase_03 | AC | 357 ms
11,264 KB |
testcase_04 | AC | 481 ms
38,960 KB |
testcase_05 | AC | 325 ms
7,296 KB |
testcase_06 | AC | 321 ms
18,272 KB |
testcase_07 | AC | 322 ms
18,400 KB |
testcase_08 | AC | 239 ms
18,400 KB |
testcase_09 | AC | 530 ms
38,376 KB |
testcase_10 | AC | 135 ms
38,356 KB |
ソースコード
#pragma GCC optimize("O3")#include <iostream>#include <iomanip>#include <cstdio>#include <string>#include <cstring>#include <deque>#include <list>#include <queue>#include <stack>#include <vector>#include <utility>#include <algorithm>#include <map>#include <set>#include <complex>#include <cmath>#include <limits>#include <cfloat>#include <climits>#include <ctime>#include <cassert>#include <numeric>#include <fstream>#include <functional>#include <bitset>using namespace std;using ll = long long;using P = pair<int, int>;using T = tuple<int, int, int>;template <class T> inline T chmax(T &a, const T b) {return a = (a < b) ? b : a;}template <class T> inline T chmin(T &a, const T b) {return a = (a > b) ? b : a;}constexpr int MOD = 1e9 + 7;constexpr int inf = 1e9;constexpr long long INF = 1e18;#define all(a) (a).begin(), (a).end()int dx[] = {1, 0, -1, 0};int dy[] = {0, 1, 0, -1};class UnionFind{public:vector<int> par;vector<int> rank;vector<int> sz;vector<int> sum;vector<vector<int>> children;int uf_size;UnionFind(int n){par.resize(n);rank.resize(n);sz.resize(n);sum.resize(n);children.resize(n);uf_size = n;for(int i=0; i<n; i++){par[i] = i;rank[i] = 0;sum[i] = 0;sz[i] = 1;children[i].emplace_back(i);}}int find(int x){if(par[x] == x) return x;else return par[x] = find(par[x]);}bool same(int x, int y){return find(x) == find(y);}int get(int x){return x == par[x] ? sum[x] : sum[x] + sum[find(x)];}bool unite(int x, int y){x = find(x);y = find(y);if(x == y) return false;if(rank[x] < rank[y]) swap(x, y);if(rank[x] == rank[y]) rank[x]++;uf_size--;par[y] = x;sz[x] = sz[x] + sz[y];int sub = sum[y] - sum[x];sum[y] = 0;for(auto i : children[y]){children[x].emplace_back(i);sum[i] += sub;}children[y].clear();return true;}int size(int x){return sz[find(x)];}};int main(){cin.tie(0);ios::sync_with_stdio(false);int n, q; cin>>n>>q;UnionFind uf(n);for(int i=0; i<q; i++){int t, a, b; cin>>t>>a>>b;if(t == 1){uf.unite(a - 1, b - 1);}else if(t == 2){int parent = uf.find(a - 1);uf.sum[parent] += b;}else{cout << uf.get(a - 1) << endl;}}return 0;}