Cod sursa(job #1832159)

Utilizator Marius_mFMI-M2 Marius Melemciuc Marius_m Data 19 decembrie 2016 15:44:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
/*
 * =====================================================================================
 *
 *       Filename:  IA_paduri_de_multimi_disjuncte_disjoint_data_set.cpp
 *
 *    Description:  http://www.infoarena.ro/problema/disjoint
 *
 *        Version:  1.0
 *        Created:  04/04/2016 12:44:12 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  Marius-Constantin Melemciuc
 *          email:
 *   Organization:
 *
 * =====================================================================================
 */
  
#include <iostream>
#include <vector>
#include <fstream>
  
using namespace std;
  
class DisjointDataSet {
    /**
     * The term rank is used instead of depth since it stops
     * being equal to the depth if path compression is also used.
     * Actually, rank is an upper bound on height. 
     */
    vector<int> rank;
    vector<int> parent;
public:
    DisjointDataSet(int);
    ~DisjointDataSet();
    int getRoot(int);
    void link(int, int);
    void unionSets(int, int);
};
  
DisjointDataSet::DisjointDataSet(int n) {
    rank.resize(n + 1, 0);
    parent.resize(n + 1);
    for (int i = 0; i < n + 1; i++) {
        parent[i] = i;
    }
}
  
DisjointDataSet::~DisjointDataSet() {
}
  
int DisjointDataSet::getRoot(int x) {
    int i;
  
    for (i = x; parent[i] != i; i = parent[i]) {
    }
      
    // i is the root
    int aux;
    while (parent[x] != x) {  // path compression
        aux = parent[x];
        parent[x] = i;
        x = aux;
    }
    return i;
}
  
void DisjointDataSet::link(int x, int y) {
    if (rank[x] < rank[y]) {        // union by rank
        parent[x] = y;
    } else {
        if (rank[x] > rank[y]) {
            parent[y] = x;
        } else {
            parent[x] = y;
            rank[y]++;
        }
    }
}
  
void DisjointDataSet::unionSets(int x, int y) {
    link(getRoot(x), getRoot(y));
}
  
int main() {
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");
  
    int n;
    int numOperations;
  
    in >> n >> numOperations;
  
    DisjointDataSet d(n);
  
    int operation, x, y;
    for (int i = 0; i < numOperations; i++) {
        in >> operation >> x >> y;
        if (operation == 1) {
            d.unionSets(x, y);
        }
        if (operation == 2) {
            if (d.getRoot(x) == d.getRoot(y)) {
                out << "DA";
            } else {
                out << "NU";
            }
            out << "\n";
        }
    }
  
    in.close();
    out.close();
  
    return 0;
}