Cod sursa(job #1312852)

Utilizator Marius_mFMI-M2 Marius Melemciuc Marius_m Data 9 ianuarie 2015 23:40:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
/*
 * =====================================================================================
 *
 *       Filename:  disjoint_set.cpp
 *
 *    Description:  http://www.infoarena.ro/problema/disjoint
 *
 *        Version:  1.0
 *        Created:  01/09/2015 23:23:26
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <iostream>
#include <cstdio>
#define NMAX 100001

using namespace std;

class DisjointDataSet 
{
	int parent[NMAX];
	int rang[NMAX];
public:
	DisjointDataSet();
	~DisjointDataSet();
	void makeSet(int);
	int findRoot(int);
	void link(int, int);
	void unionSets(int, int);
};

DisjointDataSet::DisjointDataSet()
{
}

DisjointDataSet::~DisjointDataSet()
{
}

void DisjointDataSet::makeSet(int x)
{
	parent[x] = x;
	rang[x] = 1;
}

int DisjointDataSet::findRoot(int x)
{
	int i;

	for (i = x; parent[i] != i; i = parent[i])
		;

	// i is the root
	// now we compute path compression 
	while (parent[x] != x)
	{
		int aux = parent[x];
		parent[x] = i;
		x = aux;
	}

	return i;
}

void DisjointDataSet::link(int x, int y)
{
	if (rang[x] < rang[y])
		parent[x] = y;
	else 
		if (rang[x] > rang[y])
			parent[y] = x;
		else 
		{
			parent[x] = y;
			rang[y]++;
		}
}

void DisjointDataSet::unionSets(int x, int y)
{
	link(findRoot(x), findRoot(y));
}

int main(int argc, char** argv)
{
    FILE *in, *out;
    int operation, x, y;
    int n, m;
 
    DisjointDataSet d;
 
    in  = fopen("disjoint.in", "r");
    out = fopen("disjoint.out", "w");
 
    fscanf(in, "%d %d", &n, &m);
     
    for (int i = 1; i <= n; i++)
        d.makeSet(i);
 
    for (int i = 0; i < m; i++)
    {
        fscanf(in, "%d %d %d", &operation, &x, &y);
         
        if (operation == 1)
            d.unionSets(x, y);
        else
            if (operation == 2)
            {
                if (d.findRoot(x) == d.findRoot(y))
                    fprintf(out, "DA\n");
                else
                    fprintf(out, "NU\n");   
            }
    }
 
    return 0;
}