Cod sursa(job #2721943)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 12 martie 2021 14:43:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

const int NMax = 1e5;

int n, m;
int father[NMax + 5], height[NMax + 5];

int Root(int node){
    while (father[node])
        node = father[node];
    return node;
}

void Join(int node1, int node2){
    int root1, root2;
    root1 = Root(node1);
    root2 = Root(node2);
    if (height[root1] < height[root2]){
        father[root1] = root2;
        height[root2] = max(height[root2], height[root1] + 1);
    }
    else{
        father[root2] = root1;
        height[root1] = max(height[root1], height[root2] + 1);
    }
}

void Query(int node1, int node2){
    int root1, root2;
    root1 = Root(node1);
    root2 = Root(node2);
    if (root1 == root2)
        fout << "DA" << '\n';
    else
        fout << "NU" << '\n';
}

int main(){
    fin >> n >> m;
    int type, x, y;
    while (m--){
        fin >> type >> x >> y;
        if (type == 1)
            Join(x, y);
        if (type == 2)
            Query(x, y);
    }
    return 0;
}