Cod sursa(job #360231)

Utilizator serbanlupulupulescu serban serbanlupu Data 30 octombrie 2009 17:48:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <algorithm>

using namespace std;

int vect[100001];
stack<int > S;

int father(int i)
{
	int father=i;
	
	while ( vect[father] != 0)
	{
		S.push(father);
		father=vect[father];
	}
	while (!S.empty())
	{
		vect[S.top()]=father;
		S.pop();
	}
	return father;
}

void join(int i, int j)
{
	if (vect[i] == 0)
		vect[i]=j;
	else
		if (vect[j] == 0)
			vect[j]=i;
		else
			vect[father(i)]=j;
}

void solve(const char * buff_file, const char * out_file)
{
	fstream f(buff_file, ios::in);
	fstream g(out_file, ios::out);
	
	int nodes;
	int m;
	f>>nodes>>m;
	
	int dec, left, right;
	for (int i=1; i<=m; ++i)
	{
		f>>dec>>left>>right;
		
		if ( dec == 1 )
			join(left, right);
		if ( dec == 2 )
		{
			if (father(left)==father(right))
				g<<"DA\n";
			else
				g<<"NU\n";
		}
	}
}

int main()
{
	solve("disjoint.in", "disjoint.out");
	return 0;
}