Cod sursa(job #1222384)

Utilizator roxana.istratePoenaru Roxana roxana.istrate Data 23 august 2014 00:01:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <stack>
#include <vector>
#include <utility>

using namespace std;

class TreeNode{
public:
	int val;
	TreeNode *parent;
	TreeNode *child_to_update;
	TreeNode(int v) : val(v), parent(NULL), child_to_update(NULL) {}

};

int n, m, op, a, b;
vector<struct TreeNode*> trees;
vector<int> ranks;

void make_set(int a){
	trees.push_back(new TreeNode(a));
}

int find(int a){
	TreeNode *t = trees.at(a), *aux, *rad;
	int ret;
	while(t->parent != NULL){
		aux = t;
		t = t->parent;
		t->child_to_update = aux; 
	}
	rad = t;
	while((aux = t->child_to_update)){
		t->child_to_update = NULL;
		aux->parent = rad;
		t = aux;
	}
	return rad->val;
}

void link(int a, int b){
	int pa = find(a);
	int pb = find(b);
	TreeNode *ppa = trees.at(pa);
	TreeNode *ppb = trees.at(pb);
	ppb->parent = ppa;
}

void uunion(int a, int b){
	if(ranks.at(a) > ranks.at(b)){
		link(a, b);
	}else{
		link(b, a);
		if(ranks.at(a) == ranks.at(b)){
			ranks.at(b)++;
		}
	}
}

int main(){
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
	scanf("%d%d", &n, &m);
	for(int i = 0; i < n; i++){
		make_set(i);
		ranks.push_back(0);
	}
	for(int i = 0; i < m; i++){
		scanf("%d%d%d", &op, &a, &b);
		a--, b--;
		switch(op){
		case 1: 
			uunion(a, b);
			break;
		case 2: 
			(find(a) == find(b))? printf("DA\n") : printf("NU\n");
		}
	}
}