Cod sursa(job #2916548)

Utilizator MR0L3eXMaracine Constantin Razvan MR0L3eX Data 30 iulie 2022 14:39:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 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;
	}
};

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
 
int main() {
	int n, m;
	fin >> n >> m;
	DSU dsu(n);
	while (m--) {
		int ty, a, b;
		fin >> ty >> a >> b;
		--a, --b;
		if (ty == 1) {
			dsu.unite(a, b);
		} else {
			fout << (dsu.same_set(a, b) ? "DA" : "NU") << nl;
		}
	}
}