結果

問題 No.1054 Union add query
ユーザー southball02southball02
提出日時 2020-05-15 22:02:39
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 192 ms / 2,000 ms
コード長 1,672 bytes
コンパイル時間 2,376 ms
コンパイル使用メモリ 201,300 KB
実行使用メモリ 7,448 KB
最終ジャッジ日時 2023-10-19 14:24:31
合計ジャッジ時間 5,013 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
7,440 KB
testcase_01 AC 5 ms
7,440 KB
testcase_02 AC 4 ms
7,440 KB
testcase_03 AC 150 ms
7,448 KB
testcase_04 AC 192 ms
7,448 KB
testcase_05 AC 145 ms
7,448 KB
testcase_06 AC 152 ms
7,448 KB
testcase_07 AC 122 ms
7,448 KB
testcase_08 AC 143 ms
7,448 KB
testcase_09 AC 181 ms
7,448 KB
testcase_10 AC 100 ms
7,444 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

template<typename H> bool chmin(H& v1, const H v2) { if (v1 > v2) { v1 = v2; return true; } return false; }
template<typename H> bool chmax(H& v1, const H v2) { if (v1 < v2) { v1 = v2; return true; } return false; }
template<typename H> void read(H& head) { cin >> head; }
template<typename H, typename ...T> void read(H& head, T& ...tail) { cin >> head; read(tail...); }
template<typename H> void write(H head) { cout << head << '\n'; }
template<typename H, typename ...T> void write(H head, T ...tail) { cout << head << " "; write(tail...); }
template<typename ...T> void die(T ...tok) { write(tok...); exit(0); }

struct Dsu {
	int dsu[500005];
	int v[500005];
	Dsu() { fill(dsu, dsu + 500005, -1), fill(v, v + 500005, 0); }
	int find(int x) { return dsu[x] < 0 ? x : find(dsu[x]); }
	void merge(int a, int b) {
		a = find(a), b = find(b);
		if (a == b) return;
		// union by rank
		int ra = -dsu[a], rb = -dsu[b];
		if (ra < rb) swap(a, b);
		// glue u <- v
		dsu[a] += dsu[b];
		dsu[b] = a;
		while (a >= 0) {
			v[b] -= v[a];
			a = dsu[a];
		}
	}
};

Dsu dsu;

int main() {
	cin.tie(0)->sync_with_stdio(0);
	cin.exceptions(cin.failbit);

	int n, q; read(n, q);
	rep(i, 0, q) {
		int t, a, b; read(t, a, b); 
		if (t == 1) {
			dsu.merge(a, b);
		} else if (t == 2) {
			a = dsu.find(a);
			dsu.v[a] += b;
		} else if (t == 3) {
			int cv = 0;
			while (a >= 0) {
				cv += dsu.v[a];
				a = dsu.dsu[a];
			}
			write(cv);
		}
	}
}
0