Cod sursa(job #2864703)

Utilizator lucamLuca Mazilescu lucam Data 8 martie 2022 09:46:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

const int N = 1e5 + 1;

int n, q;
int t[N], rg[N];

int root(int x) {
	int y = x;
	while (t[y] != 0) {
		y = t[y];
	}
	while (x != y) {
		int ox = t[x];
		t[x] = y;
		x = ox;
	}
	return y;
}

void op_union(int x, int y) {
	int rx = root(x), ry = root(y);
	if (rx == ry) {
		return;
	}
	if (rg[rx] < rg[ry]) {
		swap(rx, ry);
	}
	t[rx] = ry;
	rg[rx] += rg[ry];
}

bool op_same_root(int x, int y) {
	return root(x) == root(y);
}

int main() {
	in >> n >> q;
	fill(rg + 1, rg + n + 1, 1);
	while (q--) {
		int op, x, y;
		in >> op >> x >> y;
		if (op == 1) {
			op_union(x, y);
		} else {
			out << (op_same_root(x, y) ? "DA" : "NU") << '\n';
		}
	}
}