Cod sursa(job #2936150)

Utilizator iulia.talpalariuIulia-Georgiana Talpalariu iulia.talpalariu Data 8 noiembrie 2022 10:39:09
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 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) {
    while (parent[x] != 0)
        x = parent[x];
    return x;
}



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] = r[r1] + 1;
        }
    }
}




void Graph:: rezolva() {
    fileIn >> N >> M;
    parent.resize(N + 1, 0);
    for(int i = 0 ; i <=N; i++) {
        parent[i] = i;
    }
    r.resize(N + 1, 1);
    int op, a, b;
    while(M) {
        fileIn >> op >> a >> b;
        if (op == 1) {
            if(reprez(a) != reprez(b)) {
               reuneste(a,b);
               }
        } else {
            if (reprez(a) == reprez(b)) {
                fileOut << "DA\n";
            } else {
                fileOut << "NU\n";

            }
        }
        M--;
    }



}


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


    return 0;

}