Cod sursa(job #1739822)

Utilizator Marius_mFMI-M2 Marius Melemciuc Marius_m Data 10 august 2016 12:28:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
/*
 * =====================================================================================
 *
 *       Filename:  infoarena_disjoint_data_set_paduri_de_multimi_disjuncte.cpp
 *
 *    Description:  http://www.infoarena.ro/problema/disjoint
 *
 *        Version:  1.0
 *        Created:  08/10/2016 12:07:14 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  Marius-Constantin Melemciuc  
 *          email:  
 *   Organization:  
 *
 * =====================================================================================
 */

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

class DisjointDataSet {
    vector<int> parent;
    vector<int> rang; 
    int n;
public:
    DisjointDataSet(int);
    ~DisjointDataSet();
    int findRoot(int);
    void link(int, int);
    void unionSets(int, int);
};

DisjointDataSet::DisjointDataSet(int numberOfSets) {
    n = numberOfSets; 
    rang.resize(n + 1, 0);
    parent.resize(n + 1);

    for (int i = 0; i < parent.size(); i++) {
        parent[i] = i;
    }
}

DisjointDataSet::~DisjointDataSet() {
}

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

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

    //i is the root number 
    //path compression
    int aux; 
    while (parent[x] != x) {
        aux = parent[x]; 
        parent[x] = i;
        x = aux;
        rang[i]--;
    }

    return i;
}

void DisjointDataSet::link(int x, int y) {
    // reuniunea dupa rang
    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() {
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    int n, m;

    in >> n >> m;

    int operation, x, y;
    DisjointDataSet obj(n);

    for (int i = 0; i < m; i++) {
        in >> operation >> x >> y;
        if (operation == 1) {
            obj.unionSets(x, y);
        }
        if (operation == 2) {
            if (obj.findRoot(x) == obj.findRoot(y)) {
                out << "DA";
            } else {
                out << "NU";
            }
            out << "\n";
        }
    }

    return 0;
}