Cod sursa(job #2973643)

Utilizator Teodor11Posea Teodor Teodor11 Data 1 februarie 2023 15:21:55
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 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);
    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";
            }
        }
    }
    return 0;
}