Cod sursa(job #2933048)

Utilizator asparagusNadu Toma asparagus Data 4 noiembrie 2022 15:53:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>
using namespace std;


bool areInTheSameSet(int firstNode, int secondNode, const int *parentArray) {
    while (parentArray[firstNode] != -1)
        firstNode = parentArray[firstNode];

    while (parentArray[secondNode] != -1)
        secondNode = parentArray[secondNode];

    if (firstNode == secondNode)
        return true;

    return false;
}


void uniteSets(int firstNode, int secondNode, int *parentArray, int *heights) {
    if (areInTheSameSet(firstNode, secondNode, parentArray))
        return;

    while (parentArray[firstNode] != -1)
        firstNode = parentArray[firstNode];

    while (parentArray[secondNode] != -1)
        secondNode = parentArray[secondNode];

    if (heights[firstNode] < heights[secondNode])
        parentArray[firstNode] = secondNode;
    else {
        parentArray[secondNode] = firstNode;

        if (heights[secondNode] == heights[firstNode])
            heights[firstNode]++;
    }
}


int main() {
    ifstream input;
    input.open("disjoint.in");

    ofstream output;
    output.open("disjoint.out");

    int numberOfSets, numberOfOperations, operationType, firstNode, secondNode;
    input >> numberOfSets >> numberOfOperations;

    int parentArray[numberOfSets], heights[numberOfSets];
    for (int i = 0; i < numberOfSets; i++)
        parentArray[i] = -1, heights[i] = 1;


    for (int i = 0; i < numberOfOperations; i++) {
        input >> operationType >> firstNode >> secondNode;
        firstNode--, secondNode--;

        if (operationType == 2) {
            if (areInTheSameSet(firstNode, secondNode, parentArray))
                output << "DA\n";
            else
                output << "NU\n";
        } else uniteSets(firstNode, secondNode, parentArray, heights);
    }

    output.close();
    input.close();

    return 0;
}