Cod sursa(job #1034829)

Utilizator SzymonSidorSzymonSidor SzymonSidor Data 18 noiembrie 2013 06:47:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <algorithm>
#include <iostream>
#include <fstream>

using namespace std;

int tata[100010];
int rang[100010];

int inline root(int nod) {
	if (tata[nod] != nod)
		tata[nod] = root(tata[nod]);

	return tata[nod];
}

void unify(int x, int y) {
	x = root(x);
	y = root(y);

	if (rang[x] == rang[y])
		tata[x] = y, rang[y]++;
	else if (rang[x] < rang[y])
		tata[x] = y;
	else tata[y] = x;
}

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

	int n, m;
	cin >> n >> m;

	for (int i = 1; i <= n; i++)
		tata[i] = i, rang[i] = 1;

	for (; m; m--) {
		int tip, x, y;
		cin >> tip >> x >> y;

		if (tip == 1)
			unify(x, y);
		else cout << ((root(x) == root(y))? "DA\n" : "NU\n");
	}

	return 0;
}