Cod sursa(job #495534)

Utilizator bog29Antohi Bogdan bog29 Data 25 octombrie 2010 19:17:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include<fstream>
#define dmax 100004
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");

int n,m,op,x,y,f[dmax],h[dmax];

void uneste(int x,int y)
{	while(f[x])
		x=f[x];
	while(f[y])
		y=f[y];
	
	if(h[x] < h[y])
		f[x]=y;	
	else if(h[y] < h[x])
		f[y]=x;
	else if(h[x] == h[y])
	{	f[y]=x;
		h[x]++;
	}	
}

void cauta(int x,int y)
{	int xx,yy;

	xx=x, yy=y;
	
	while(f[x])
		x=f[x];
	while(f[y])
		y=f[y];
	if(x == y)
		out<<"DA\n";
	else out<<"NU\n";
	
	/*while(f[xx])
	{	f[xx]=x;
		x=f[x];
	}
	while(f[yy])
	{	f[yy]=y;
		y=f[y];
	}	*/
}


int main()
{	int i;
	in>>n>>m;
	for(i=1;i<=n;i++)
		h[i]=1;
	for(i=1;i<=m;i++)
	{	in>>op>>x>>y;
		if(op==1)
			uneste(x,y);
		if(op==2)
			cauta(x,y);
	}
	in.close();
	
	out.close();
	return 0;
}