Cod sursa(job #947912)

Utilizator tibi9876Marin Tiberiu tibi9876 Data 8 mai 2013 20:20:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include<fstream>
using namespace std;

int a[100001],v[100001],i,n,m,x,y,c,p,z,t;

int main()
{
	ifstream f("disjoint.in");
	ofstream g("disjoint.out");
	f >> n >> m;
	for (i=1;i<=n;i++)
	{
		a[i]=i;
		v[i]=1;
	}
	for (i=1;i<=m;i++)
	{
		f >> c >> x >> y;
		if (c==1)
		{
			while (a[x]!=x)
				x=a[x];
			while (a[y]!=y)
				y=a[y];
			if (v[x]<v[y])
				a[x]=y;
			else if (v[x]>v[y])
				a[y]=x;
			else
			{
				a[x]=y;
				v[x]++;
			}
		}
		else
		{
			z=x;t=y;
			while (a[z]!=z)
				z=a[z];
			while (a[t]!=t)
				t=a[t];
			while (a[x]!=x)
			{
				p=a[x];
				a[x]=z;
				x=p;
			}
			while (a[y]!=y)
			{
				p=a[y];
				a[y]=t;
				y=p;
			}
			if (x==y)
				g << "DA\n";
			else g << "NU\n";
		}
	}
	return 0;
}