Cod sursa(job #1428735)

Utilizator AlexandraaaaMereu Alexandra Alexandraaaa Data 4 mai 2015 23:45:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>

using namespace std;

const int Nmax = 100020;
int rg[Nmax], tata[Nmax];

int urca(int x) {
	int y, a = x;
	while (tata[x] != x)
		x = tata[x];
	while (tata[a] != x) {
		y = tata[a];
		tata[a] = x;
		a = y;
	}
	return x;
}

void unire (int a, int b) {
	if (rg[a] > rg[b]) {
		rg[a]++;
		tata[b] = a;
	}	else {
		rg[b]++;
		tata[a] = b;
	}
}

int main()
{
	int n, m, x, y, c, i;
	ifstream f("disjoint.in");
	ofstream g("disjoint.out");
	f >> n >> m;
	for (i = 1; i <= n; i++) {
		rg[i] = 1;
		tata[i] = i;
	}
	for (i = 1; i <= m; i++) {
		f >> c >> x >> y;
		if (c == 1)
			unire(urca(x), urca(y));
		else
			if (urca(x) == urca(y))
				g << "DA\n";
			else
				g << "NU\n";
	}
	f.close();
	g.close();
	//cin.get();
	return 0;
}