Cod sursa(job #2946531)

Utilizator DevCrutCorolevschi Mihai DevCrut Data 24 noiembrie 2022 23:00:39
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <string.h>
#include <vector>
#include <cmath>
#include <queue>
#include <iostream>


using namespace std;

vector<pair<int, int>> vec;
int maxN, opCount, opType, a, b;

int GetRoot(int a) {
    while (vec[a].first != -1) {
        a = vec[a].first;
    }
    return a;
}

void UnionSet(int a, int b) {
    int rootA = GetRoot(a);
    int rootB = GetRoot(b);

    int distA = vec[rootA].second;
    int distB = vec[rootB].second;

    if (distA <= distB) {
        vec[rootA] = { rootB, distA + 1 };
    }
    else {
        vec[rootB] = { rootA, distB + 1 };
    }
}

int main() {
    ifstream myIn("disjoint.in");
    myIn >> maxN >> opCount;

    vec.resize(maxN, { -1,0 });

    ofstream myOut("disjoint.out");
    for (int i = 0; i < opCount; i++) {
        myIn >> opType >> a >> b;
        a -= 1; b -= 1;

        if (opType == 1) {
            // reuniune
            UnionSet(a, b);
        }
        else {
            // bool
            if (GetRoot(a) == GetRoot(b)) {
                myOut << "DA" << endl;
            }
            else {
                myOut << "NU" << endl;
            }
        }
    }
    myOut.close();
    return 0;
}