Cod sursa(job #2513618)

Utilizator ioanasIoana S ioanas Data 23 decembrie 2019 15:28:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <vector>

#define MAXV	100001

using namespace std;

vector<int> p (MAXV);

int root(int x) {
	int aux = x;
	while (p[x] !=x) {
		x = p[x];
	}
	while (p[aux] != aux) {
		int next = p[aux];
		p[aux] = x;
		aux = next;
}
	return x;
}

void uni(int x, int y) {
	int rx = root(x), ry = root(y);
	if ((x + y) % 2) p[ry] = rx;
	else p[rx] = ry;
}

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

int main() {
	ifstream in ("disjoint.in");
	ofstream out("disjoint.out");

	int n, m;
	in >> n >> m;

	for (int i = 1; i <= n; ++i)
		p[i] = i;

	int cod, x, y;
	for (int i = 0; i < m; ++i) {
		in >> cod >> x >> y;
		
		if (cod == 1) {
			uni(x, y);
		} else {
			if (find(x, y)) out << "DA\n";
			else out << "NU\n";
		}
	}
}