Cod sursa(job #2936176)

Utilizator iulia.talpalariuIulia-Georgiana Talpalariu iulia.talpalariu Data 8 noiembrie 2022 11:27:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <vector>
#include <fstream>

using namespace std;
ifstream fileIn("disjoint.in");
ofstream fileOut("disjoint.out");


class Graph {
    int N;
    int M;
    vector <int> r;
    vector <int> parent;

    public:
        int reprez(int x);
        void reuneste(int a, int b) ;
        void rezolva();


};

int Graph::reprez(int x) {
    int reprezentant = x;
    while (parent[reprezentant] != 0) {
        reprezentant = parent[reprezentant];
    }

    int y;
    while(parent[x]!=0) {
        y = parent[x];
        parent[x] = reprezentant;
        x = y;
    }
    return reprezentant;
}



void Graph::reuneste(int a, int b) {
    int r1 = reprez(a);
    int r2 = reprez(b);

    if(r[r1] > r[r2]) {
        parent[r2] = r1;
    } else {
        parent[r1] = r2;
        if (r[r1] == r[r2] ) {
            r[r2]++;
        }
    }
}




void Graph:: rezolva() {

    fileIn >> N >> M;

    parent.resize(N + 1, 0);
    r.resize(N + 1, 1);


    int op, a, b;

    while(M) {
        M--;
        fileIn >> op >> a >> b;
        if (op == 1) {
               reuneste(a,b);

        } else {
            if (reprez(a) == reprez(b)) {
                fileOut << "DA\n";
            } else {
                fileOut << "NU\n";

            }
        }

    }



}


int main()  {
    Graph my_graph;
    my_graph.rezolva();


    return 0;

}