Cod sursa(job #1790546)

Utilizator Firealex2Rotileanu Alexandru Firealex2 Data 28 octombrie 2016 13:23:05
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

ifstream fi("disjoint.in");
ofstream fo("disjoint.out");

struct node {
	int data, rank;
	node* father;
};

node* FIND(node* x);
void UNION(int x, int y);
void init();

node* sets[100001];
int N, Q;

int main()
{
	init();
	for (int i = 1;i <= Q;i++)
	{
		int c, x, y;
		fi >> c >> x >> y;
		if (c == 2)
		{
			if (FIND(sets[x]) == FIND(sets[y]))
				fo << "DA\n";
			else fo << "NU\n";
		}
		else
			UNION(x, y);
	}
}

void init()
{
	fi >> N >> Q;
	for (int i = 1;i <= N;i++)
	{
		node* n = new node;
		n->data = i;
		n->father = NULL;
		n->rank = 1;
		sets[i] = n;
	}
}

void UNION(int x, int y)
{
	
	if (sets[y]->rank < sets[x]->rank)
	{
		node* n = sets[y];
		while (n->father != NULL)
			n = n->father;
		sets[n->data]->father = sets[x];
		sets[y]->rank += sets[x]->rank;
	}
	else
	{
		node* n = sets[x];
		while (n->father != NULL)
			n = n->father;
		sets[n->data]->father = sets[y];
		sets[x]->rank += sets[y]->rank;
	}
	return;
}

node* FIND(node* x)
{
	if (x->father != NULL)
		x->father = FIND(x->father);
	return x;
}