Cod sursa(job #2224048)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 22 iulie 2018 16:36:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <vector>
#include <string>

using namespace std;

const string IN_FILE = "disjoint.in";
const string OUT_FILE = "disjoint.out";
const int NIL = -1;

class DisjointSets {
  public:
    DisjointSets(const int _size) :
        size(_size),
        parent(vector<int>(_size, NIL)) {}

    int find(const int x) {
        return parent[x] == NIL ? x : parent[x] = find(parent[x]);
    }

    bool merge(const int x, const int y) {
        const int rx = find(x);
        const int ry = find(y);
        if (rx == ry) return false;
        parent[ry] = rx;
        return true;
    }

  private:
    int size;
    vector<int> parent;
};

int main() {
    ifstream in(IN_FILE);
    ofstream out(OUT_FILE);
    int n, m;
    in >> n >> m;
    auto sets = DisjointSets(n);
    for (int i = 0; i < m; i++) {
        int type, x, y;
        in >> type >> x >> y;
        if (type == 1) {
            sets.merge(x - 1, y - 1);
        } else {
            out << (sets.find(x - 1) == sets.find(y - 1) ? "DA" : "NU") << "\n";
        }
    }
    return 0;
}