Cod sursa(job #795298)

Utilizator radustn92Radu Stancu radustn92 Data 8 octombrie 2012 00:23:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <stdio.h>
#define NMAX 100005
int n,m,root[NMAX],grd[NMAX];
void init()
{
	int i;
	for (i=1; i<=n; i++)
		root[i]=i,grd[i]=1;
}
inline int find_root(int nod)
{
	int x=nod,y;
	while (root[x]!=x)
		x=root[x];
	while (root[nod]!=nod)
	{
		y=nod;
		nod=root[nod];
		root[y]=x;
	}
	return x;
}
void unite(int x,int y)
{
	if (grd[x]<grd[y])
		root[x]=y,grd[y]+=grd[x];
	else
		root[y]=x,grd[x]+=grd[y];
}
void check(int x,int y)
{
	if (find_root(x)!=find_root(y))
		printf("NU\n");
	else
		printf("DA\n");
}
int main()
{
	freopen("disjoint.in","r",stdin);
	freopen("disjoint.out","w",stdout);
	scanf("%d%d",&n,&m);
	init();
	int i,tip,x,y;
	for (i=1; i<=m; i++)
	{
		scanf("%d%d%d",&tip,&x,&y);
		if (tip==1)
			unite(find_root(x),find_root(y));
		if (tip==2)
			check(x,y);
	}
	return 0;
}