Cod sursa(job #2979061)

Utilizator Teodor11Posea Teodor Teodor11 Data 14 februarie 2023 19:09:16
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
using namespace std;

const int NMAX = 100005;
int n, m, x, y, code, parent[NMAX];

/// we need to find the root of a tree

int findRoot(int node) {
    if (!parent[node]) {
        return node;
    }
    return findRoot(parent[node]);
}

/// we need to unite two trees

void uniteTrees(int node1, int node2) {
    int node1Root = findRoot(node1), node2Root = findRoot(node2);
    /*
    cout << "x: " << node1 << endl;
    cout << "y: " << node2 << endl;
    cout << "Root of x: " << node1Root << endl;
    cout << "Root of y: " << node2Root << endl;
    */
    if (node1Root != node2Root) {
        parent[node1Root] = node2Root;
    }
}

int main() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    fin >> n >> m;

    for (int i = 0; i < m; ++i) {
        fin >> code >> x >> y;
        if (code == 1) {
            //parent[x] = y;
            uniteTrees(x, y);
        } else {
            if (findRoot(x) == findRoot(y)) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
        /*
        for (int j = 1; j <= n; ++j) {
            cout << parent[j] << ' ';
        }
        cout << endl << endl;
        */
    }
    /*
    for (int i = 1; i <= m; ++i) {
        fin >> x >> y;
        parent[x] = y;
    }
    */
    for (int i = 1; i <= n; ++i) {
        cout << "Root of node " << i << ": " << findRoot(i) << endl;
    }
    return 0;
}