Cod sursa(job #1249782)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 27 octombrie 2014 14:22:56
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>

#define Nmax 100100

using namespace std;

class Forest {

    private:
        int Father[Nmax], Length[Nmax];

    public:

        void init(int N) {

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

        }

        int root(int Node) {

            if(Node != Father[Node])
                return root(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;

            if(Length[A] < Length[B])
                Father[A] = B;
            else
                Father[B] = A;

            if(Length[A] == Length[B])
                Length[A]++;

        }

};

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;

}