結果

問題 No.1054 Union add query
ユーザー yudedakoyudedako
提出日時 2020-08-27 14:28:21
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 141 ms / 2,000 ms
コード長 1,589 bytes
コンパイル時間 831 ms
コンパイル使用メモリ 110,876 KB
実行使用メモリ 7,168 KB
最終ジャッジ日時 2024-04-25 07:14:07
合計ジャッジ時間 4,054 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 123 ms
5,376 KB
testcase_04 AC 138 ms
7,040 KB
testcase_05 AC 122 ms
5,376 KB
testcase_06 AC 123 ms
5,376 KB
testcase_07 AC 116 ms
5,376 KB
testcase_08 AC 128 ms
5,376 KB
testcase_09 AC 141 ms
7,168 KB
testcase_10 AC 94 ms
7,040 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <utility>
#include <tuple>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <climits>
#include <numeric>
#include <queue>
#include <cmath>
#include <iomanip>
#include <array>
#include <string>
#include <stack>
#include <cassert>
#include <memory>
#include <random>
#include <fstream>
#include <cfloat>
#include <complex>



class UnionFind {
	std::vector<int> parent, added;
public:
	UnionFind(int size): parent(size, -1), added(size, 0){}
	int find(int a) {
		if (parent[a] < 0) {
			return a;
		}
		else {
			const auto root = find(parent[a]);
			if (parent[a] != root) {
				added[a] += added[parent[a]];
				parent[a] = root;
			}
			return root;
		}
	}
	void add(int node, int value) {
		added[find(node)] += value;
	}
	void unite(int a, int b) {
		a = find(a);
		b = find(b);
		if (a == b) return;
		if (parent[a] > parent[b]) std::swap(a, b);
		parent[a] += parent[b];
		parent[b] = a;
		added[b] -= added[a];
	}
	int value_of(int a) {
		if (parent[a] < 0) {
			return added[a];
		}
		else {
			return added[find(a)] + added[a];
		}
	}
};

int main() {
	std::cin.tie(nullptr);
	std::ios_base::sync_with_stdio(false);
	int n, q; std::cin >> n >> q;
	UnionFind uft(n);
	for (auto i = 0; i < q; ++i) {
		int t, a, b; std::cin >> t >> a >> b;
		switch(t) {
			case 1:
				uft.unite(a - 1, b - 1); break;
			case 2:
				uft.add(a - 1, b); break;
			case 3:
				std::cout << uft.value_of(a - 1) << '\n'; break;
			default: throw 0;
		}
	}
}
0