Cod sursa(job #1249781)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 27 octombrie 2014 14:21:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>

#define Nmax 100100

using namespace std;

class Forest {

    private:
        int Father[Nmax];

    public:

        void init(int N) {

            for(int i = 1; i <= N; i++)
                Father[i] = i;

        }

        int root(int Node) {

            if(Node != Father[Node])
                Father[Node] = root(Father[Node]);

            return Father[Node];

        }

        bool same(int A, int B) {

            return (root(A) == root(B));

        }

        void unite(int A, int B) {

            A = root(A);
            B = root(B);

            if(A == B)
                return;

            Father[A] = B;

        }

};

Forest F;

int main() {

    int type, x, y, N, M;

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

    in >> N >> M;

    F.init(N);

    while(M--) {

        in >> type >> x >> y;

        if(type == 1)
            F.unite(x, y);
        else if(F.same(x, y))
            out << "DA\n";
        else
            out << "NU\n";

        }

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

    return 0;

}