Cod sursa(job #904421)

Utilizator ionutmodoModoranu Ionut-Vlad ionutmodo Data 4 martie 2013 13:28:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <fstream>
using namespace std;

int n, m;
int ord[100005];

void Unite(int x, int y)
{
	if(ord[y] < ord[x])
	{
		ord[y] += ord[x];
		ord[x] = y;
	}
	else
	{
		ord[x] += ord[y];
		ord[y] = x;
	}
}

int Find(int x)
{
	int y, r = x;
	while(ord[r] > 0)
		r = ord[r];
	
	while(ord[x] > 0)
	{
		y = ord[x];
		ord[x] = r;
		x = y;
	}
	return r;
}

int main ()
{
	ifstream fin("disjoint.in");
	ofstream fout("disjoint.out");
	int i,cod,x,y;
	fin >> n >> m;
	for(i=1; i<=m; i++)
	{
		fin >> cod >> x >> y;
		if(cod == 1)
			Unite(Find(x),Find(y));
		else
			if(Find(x) == Find(y))
				fout << "DA\n";
			else
				fout << "NU\n";
	}
	fin.close();
	fout.close();
	return 0;
}