Cod sursa(job #1753272)

Utilizator dtoniucDaniel Toniuc dtoniuc Data 6 septembrie 2016 11:42:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>

using namespace std;

typedef struct elem
{
	struct elem *parent;
	int rank;
public:
	elem() {parent = this; rank = 0;}
}Elem;

void Union(Elem* x, Elem* y);
Elem* Find(Elem* x);
Elem** CreateSets(int n);

int main()
{
    ifstream fin;
    ofstream fout;
    fout.open("disjoint.out");
    fin.open("disjoint.in");

    int n, m;
    fin >> n >> m;

    Elem** elemList = CreateSets(n);

    int option, x, y;
    for(int i = 1; i <= m; i++)
    {
    	fin >> option >> x >> y;
    	switch(option)
    	{
    		case 1:
    			Union(Find(elemList[x]),Find(elemList[y]));
    			break;
    		case 2:
    			if(Find(elemList[x]) == Find(elemList[y]))
    				fout << "DA" << "\n";
    			else
    				fout << "NU" << "\n";
    			break;
    		default:
    			exit(1);
    	}
    }


    fin.close();
    fout.close();
    return 0;
}

Elem** CreateSets(int n)
{
	Elem** list = new Elem*[n + 1]();

	for (int i = 1; i <= n; i++)
	{
		list[i] = new Elem();
	}

	return list;
}

Elem* Find(Elem* x)
{
	if(x != x->parent)
		x->parent = Find(x->parent);

	return x->parent;
}

void Union(Elem* x, Elem* y)
{
	Elem* xRoot = Find(x);
	Elem* yRoot = Find(y);

	if(xRoot == yRoot)
		return;

	if(xRoot->rank > yRoot->rank)
		yRoot->parent = xRoot;
	else if(yRoot->rank > xRoot->rank)
		xRoot->parent = yRoot;
	else
	{
		yRoot->parent = xRoot;
		xRoot->rank += 1;
	}
}