Cod sursa(job #2559462)

Utilizator mariaghinescu22Ghinescu Maria mariaghinescu22 Data 27 februarie 2020 12:35:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 100001;
int n, m, type, x, y, t[N], nr[N];

int root(int x) {
	if (t[x] == 0) return x;
	t[x] = root(t[x]);
	return t[x];
}

void reunion(int x, int y) {
	int rx = root(x);
	int ry = root(y);
	if (nr[rx] < nr[ry]) {
		t[rx] = ry;
		nr[ry] += nr[rx];
	}
	else {
		t[ry] = rx;
		nr[rx] += nr[ry];
	}
}

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

int main() {
	in >> n >> m;
	for (int i = 1; i <= m; i++) {
		in >> type >> x >> y;
		if (type == 1) reunion(x, y);
		if (type == 2) {
			if (question(x, y)) out << "DA" << '\n';
			else out << "NU" << '\n';
			
		}
	}
	return 0;
}