Cod sursa(job #2916545)

Utilizator MR0L3eXMaracine Constantin Razvan MR0L3eX Data 30 iulie 2022 14:33:28
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;

const char nl = '\n';

struct DSU {
	vector<int> e;
	DSU(int N) { e = vector<int>(N, -1); }
 
	// get representive component (uses path compression)
	int get(int x) { return e[x] < 0 ? x : e[x] = get(e[x]); }
 
	bool same_set(int a, int b) { return get(a) == get(b); }
 
	int size(int x) { return -e[get(x)]; }
 
	bool unite(int x, int y) {  // union by size
		x = get(x), y = get(y);
		if (x == y) return false;
		if (e[x] > e[y]) swap(x, y);
		e[x] += e[y]; e[y] = x;
		return true;
	}
};
 
int main() {
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
	int n, m;
	cin >> n >> m;
	DSU dsu(n);
	while (m--) {
		int ty, a, b;
		cin >> ty >> a >> b;
		--a, --b;
		if (ty == 1) {
			dsu.unite(a, b);
		} else {
			cout << (dsu.same_set(a, b) ? "DA" : "NU") << nl;
		}
	}
}