Cod sursa(job #633076)

Utilizator mihaibogdan10Mihai Bogdan mihaibogdan10 Data 12 noiembrie 2011 22:34:41
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include<cstdio>
#include<vector>
using namespace std;
FILE *in = fopen("disjoint.in", "r"), *out = fopen("disjoint.out", "w");

vector <int> tata, rang;

int Find(int x){
	if (tata[x] == x) return x;
		else{
			tata[x] = Find(tata[x]);
			return tata[x];
		}
}

void Merge (int &x, int &y){
	int xRoot = Find(x), yRoot = Find(y);
	if (xRoot == yRoot) return;
	
	rang[xRoot] >= rang[yRoot] ? tata[yRoot] = xRoot : tata[xRoot] = yRoot;
	if (rang[xRoot] = rang[yRoot]) rang[xRoot]++;
}

int main(){
	int n, m, i, tip, x, y;
	fscanf(in, "%d %d", &n, &m);
	for (i = 0; i <= n; i++) tata.push_back(i);
	rang.assign(n+1, 1);
	
	for (i = 1; i <= m; i++){
		fscanf(in, "%d %d %d", &tip, &x, &y);
		if (tip == 1) Merge(x, y);
			else y == Find(x) ? fprintf(out, "DA\n") : fprintf(out, "NU\n");
	}
	
	return 0;
}