Cod sursa(job #1640050)

Utilizator cautionPopescu Teodor caution Data 8 martie 2016 15:30:25
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <vector>

class SetGroup
{
private:
    std::vector<int> v;
    inline int get(int x) {
        while(v[x] != 0) x = v[x];
        return x;
    }
    inline void mark(int x, int mark) {
        int aux;
        while(v[x] != 0) {
            aux = v[x];
            v[x] = mark;
            x = aux;
        }
    }
public:
    SetGroup() {
    }
    SetGroup(int n_sets) : v(n_sets) {
    }
    bool areJoint(int x, int y) {
        int a = get(x);
        int b = get(y);
        mark(x, a);
        mark(y, b);
        return a == b;
    }
    void uniteSets(int x, int y) {
        int a = get(x);
        int b = get(y);
        if(a != b) v[a] = b;
    }
};

int main()
{
    std::ifstream in("disjoint.in");
    std::ofstream out("disjoint.out");
    int n, m;
    in>>n>>m;
    SetGroup forest(n);
    for(int a, b, c, i = 1; i <= m; ++i) {
        in>>c>>a>>b;
        switch(c) {
            case 1:
                forest.uniteSets(a, b);
                break;
            case 2:
                if(forest.areJoint(a, b)) out<<"DA\n";
                else out<<"NU\n";
        }
    }
}