結果

問題 No.1054 Union add query
ユーザー leaf_1415leaf_1415
提出日時 2020-05-15 21:56:36
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 189 ms / 2,000 ms
コード長 1,774 bytes
コンパイル時間 2,064 ms
コンパイル使用メモリ 82,860 KB
実行使用メモリ 8,748 KB
最終ジャッジ日時 2023-10-19 14:08:04
合計ジャッジ時間 3,202 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 6 ms
8,748 KB
testcase_01 AC 7 ms
8,748 KB
testcase_02 AC 6 ms
8,748 KB
testcase_03 AC 154 ms
8,748 KB
testcase_04 AC 189 ms
8,748 KB
testcase_05 AC 148 ms
8,748 KB
testcase_06 AC 141 ms
8,748 KB
testcase_07 AC 125 ms
8,748 KB
testcase_08 AC 140 ms
8,748 KB
testcase_09 AC 172 ms
8,748 KB
testcase_10 AC 99 ms
8,748 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <string>
#include <algorithm>
#include <utility>
#define llint long long
#define inf 1e18
#define rep(x, s, t) for(llint (x) = (s); (x) < (t); (x)++)
#define Rep(x, s, t) for(llint (x) = (s); (x) <= (t); (x)++)
#define chmin(x, y) (x) = min((x), (y))
#define chmax(x, y) (x) = max((x), (y))

using namespace std;
typedef pair<llint, llint> P;

struct UnionFind{
	int size;
	vector<int> parent, rank, add;
	
	UnionFind(){}
	UnionFind(int size){
		this->size = size;
		parent.resize(size+1);
		rank.resize(size+1);
		add.resize(size+1);
		init();
	}
	void init(){
		for(int i = 0; i <= size; i++) parent[i] = i;
	}
	int root(int i){
		if(parent[i] == i) return i;
		return root(parent[i]);
	}
	bool same(int i, int j){
		return root(i) == root(j);
	}
	void addto(int i, int x){
		add[root(i)] += x;
	}
	int get(int i){
		if(parent[i] == i) return add[i];
		return add[i] + get(parent[i]);
	}
	void unite(int i, int j){
		int root_i = root(i), root_j = root(j);
		if(root_i == root_j) return;
		if(rank[root_i] < rank[root_j]){
			parent[root_i] = root_j; 
			add[root_i] -= add[root_j];
		}else{
			parent[root_j] = root_i;
			add[root_j] -= add[root_i];
			if(rank[root_j] == rank[root_j]) rank[root_i]++;
		}
	}
};

llint n, Q;
UnionFind uf(500005);

int main(void)
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> n >> Q;
	llint t, a, b;
	for(int i = 1; i <= Q; i++){
		cin >> t >> a >> b;
		if(t == 1) uf.unite(a, b);
		if(t == 2) uf.addto(a, b);
		if(t == 3) cout << uf.get(a) << "\n";
	}
	flush(cout);
	
	return 0;
}
0