Cod sursa(job #2482825)

Utilizator melutMelut Zaid melut Data 28 octombrie 2019 21:43:36
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <fstream>
#include <vector>


using namespace std;


char const *inFile = "disjoint.in";
char const *outFile = "disjoint.out";


ifstream Read(inFile);
ofstream Write(outFile);


vector<unsigned> roots;
vector<unsigned> heights;


void CompressPath(
    unsigned node,
    unsigned const root
) {
    unsigned next_node;

    while (node != roots[node]) {
        next_node = roots[node];
        roots[node] = root;
        node = next_node;
    }
}


unsigned FindRoot(
    unsigned const node
) {
    unsigned root = node;

    while (root != roots[root]) {
        root = roots[root];
    }

    CompressPath(node, root);

    return root;
}


void UniteRoots(
    unsigned const root1,
    unsigned const root2
) {
    if (heights[root1] < heights[root2]) {
        roots[root1] = root2;
    }
    else {
        roots[root2] = root1;
    }

    if (heights[root1] == heights[root2]) {
        ++heights[root1];
    }
}


int main() {
    unsigned n;
    unsigned m;
    Read >> n;
    Read >> m;

    roots.resize(n);
    heights.resize(n);

    for (unsigned i = 0; i < n; ++i) {
        roots[i] = i;
        heights[i] = 1;
    }

    unsigned task;
    unsigned node1;
    unsigned node2;
    unsigned root1;
    unsigned root2;

    for (unsigned i = 0; i < m; ++i) {
        Read >> task;
        Read >> node1;
        Read >> node2;

        --node1;
        --node2;

        if (task == 1) {
            root1 = FindRoot(node1);
            root2 = FindRoot(node2);

            if (root1 == root2) {
                continue;
            }

            UniteRoots(root1, root2);
        }
        else {
            if (FindRoot(node1) == FindRoot(node2)) {
                Write << "DA\n";
            }
            else {
                Write << "NU\n";
            }
        }
    }

    Read.close();
    Write.close();

    return 0;
}