Cod sursa(job #1377505)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 5 martie 2015 22:16:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb

#include <fstream>
#include <cstring>
#include <algorithm>

const int MAX_N(100001);

int Forest [MAX_N];

int Find (int node)
{
	if (Forest[node] < 0)
		return node;
	return Forest[node] = Find(Forest[node]);
}

inline void Union (int x, int y)
{
	x = Find(x);
	y = Find(y);
	if (x == y)
		return;
	if (Forest[x] < Forest[y])
		std::swap(x,y);
	Forest[y] += Forest[x];
	Forest[x] = y;
}

int main (void)
{
	std::memset(Forest,-1,MAX_N * sizeof(*Forest));
	std::ifstream input("disjoint.in");
	int n, m;
	input >> n >> m;
	int code, x, y;
	std::ofstream output("disjoint.out");
	while (m)
	{
		input >> code >> x >> y;
		if (code == 1)
			Union(x,y);
		else
			output << (Find(x) == Find(y) ? "DA" : "NU") << '\n';
		--m;
	}
	input.close();
	output.close();
	return 0;
}