Cod sursa(job #2946527)

Utilizator DevCrutCorolevschi Mihai DevCrut Data 24 noiembrie 2022 22:55:54
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 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;

pair<int, int> GetRoot(int a) {
    int dist = 0;
    while (vec[a].first != -1) {
        a = vec[a].first;
        dist++;
    }
    return { a, dist };
}

void UnionSet(int a, int b) {
    pair<int, int> rootA = GetRoot(a);
    pair<int, int> rootB = GetRoot(b);
    int distA = rootA.second + vec[a].second;
    int distB = rootB.second + vec[b].second;

    if (distA <= distB) {
        vec[rootA.first] = {rootB.first, distA+1};
    }
    else {
        vec[rootB.first] = { rootA.first, 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).first == GetRoot(b).first) {
                myOut << "DA" << endl;
            }
            else {
                myOut << "NU" << endl;
            }
        }
    }
    myOut.close();
    return 0;
}