Cod sursa(job #1790538)

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

using namespace std;

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

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

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

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(x) == FIND(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;
		sets[i] = n;
	}
}

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

int FIND(int x)
{
	node* n = sets[x];
	while (n->father != NULL)
		n = n->father;
	return n->data;
}