Cod sursa(job #230142)

Utilizator vlad_DVlad Dumitriu vlad_D Data 13 decembrie 2008 09:05:37
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
#include <algorithm>
#include <iostream>

using namespace std;
#define nmax 100001
int P[nmax];
int rank[nmax];
int findSet(int x) { //finds the set of x
	if (P[x] !=x) P[x] = findSet(P[x]);
	return P[x];
}
int mergeSet(int x, int y) { //combine the set of x with set of y
	int px = findSet(x);
	int py = findSet(y);
	if (rank[px] > rank[py]) P[py] = px;
	else P[px] = py;
	if (rank[px] == rank[py]) rank[py] = rank[py]+1;
}
int main() {
	ifstream fin("disjoint.in");
	ofstream fout("disjoint.out");
	int n, m;
	fin >> n >> m;
	int i, j;
	for (i = 1; i <= n; ++i) P[i] = i, rank[i] = 0;
	while (m--) {
		int c, x, y;
		fin >> c >> x >> y;
		if (c == 1) {mergeSet(x, y);continue;}
		if (findSet(x) == findSet(y)) fout << "DA";
		else fout << "NU";
		fout << '\n';

	}
	return 0;
}