Cod sursa(job #1333000)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 2 februarie 2015 17:40:57
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>

#define Nmax 100100

using namespace std;

class disjointSet {

    private:
        int size, father[Nmax], depth[Nmax];

        int root(int node) {

            if(node != father[node])
                father[node] = root(father[node]);
            else
                depth[node] = 2;

            return father[node];
        }

    public:
        void initialise(int Size) {
            size = Size;

            for(int i = 1; i <= size; i++) {
                father[i] = i;
                depth[i] = 1;
            }
        }

        void unite(int x, int y) {

            x = root(x);
            y = root(y);

            if(x == y)
                return;

            if(depth[x] < depth[y])
                father[x] = y;
            else
                father[y] = x;

            if(depth[x] == depth[y])
                depth[x]++;

            }

        bool same(int x, int y) {
            return (root(x) == root(y));
        }

} forest;

int main() {

    int type, x, y, N, queries;

    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    in >> N >> queries;
    forest.initialise(N);

    while(queries--) {

        in >> type >> x >> y;
        if(type == 1)
            forest.unite(x, y);
        else
            out << (forest.same(x, y) == true ? "DA" : "NU") << '\n';
    }

    in.close();
    out.close();

    return 0;

}