Cod sursa(job #1705636)

Utilizator mihainicolae80Mihai Nicolae mihainicolae80 Data 20 mai 2016 21:15:57
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#include <vector>
#include <list>

using namespace std;

#define NO_PARENT -1

struct Node
{
    int parent;
    int height;
    //list<int> desc;

    Node()
    {
        parent = NO_PARENT;
        height = 0;
    }
};

vector<Node> nodes;

int getroot(int x){
    if(nodes[x].parent == NO_PARENT)
        return x;

    return getroot(nodes[x].parent);
}

int main()
{

    int N, M;
    int op,x,y,i,rootx,rooty;


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

    in >> N >> M;

    nodes.resize(N);

    for(i = 1; i <= M; i++){
        in >> op >> x >> y;

        rootx = getroot(x);
        rooty = getroot(y);

        //Daca se solicita reuniunea unor multimi disjuncte
        if(op == 1){
            if(nodes[rootx].height > nodes[rooty].height){
                //Ataseaza y la x
                nodes[rooty].parent = rootx;

                if(nodes[rooty].height + 1 > nodes[rootx].height)
                    nodes[rootx].height = nodes[rooty].height + 1;
            }
            else{
                nodes[rootx].parent = rooty;

                if(nodes[rootx].height + 1 > nodes[rooty].height)
                    nodes[rooty].height = nodes[rootx].height + 1;
            }
        }
        else{
            if(rootx == rooty)
                out<<"DA"<<endl;
            else
                out<<"NU"<<endl;
        }
    }



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

    return 0;
}