Cod sursa(job #1008853)

Utilizator teoionescuIonescu Teodor teoionescu Data 11 octombrie 2013 23:13:23
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.66 kb
#include<fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
const int Nmax = 100005;
int N,M,T[Nmax],RG[Nmax];
int Query(int x){
	int R,y;
	for(R=x;T[R]!=R;R=T[R]);
	for(;T[x]!=x;){
		y=T[x];
		T[x]=R;
		x=y;
	}
	return R;
}
void Unite(int x,int y){
	x=Query(x);
	y=Query(y);
	if(RG[x]>=RG[y]){
		T[y]=x;
		if(RG[x]==RG[y]) RG[x]++;
	}
	else{
		T[x]=y;
	}
}
int main(){
	in>>N>>M;
	for(int i=1;i<=N;i++){
		T[i]=i;
		RG[i]=1;
	}
	int c,x,y;
	for(int i=1;i<=M;i++){
		in>>c>>x>>y;
		if(c==1) Unite(x,y);
		if(c==2){
			if(Query(x)==Query(y)) out<<"DA\n";
			else out<<"NU\n";
		}
	}
	return 0;
}