Cod sursa(job #3137170)

Utilizator UengineDavid Enachescu Uengine Data 11 iunie 2023 15:33:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

vector <int> father, depth;

int findrt(int node){
    if(node == father[node])
        return node;
    else
        return father[node] = findrt(father [node]);
}

void unire(int node1, int node2){
    node1 = findrt(node1);
    node2 = findrt(node2);
    if(depth[node1] > depth[node2]){
        father[node2] = node1;
    }
    else if(depth[node1] < depth[node2]){
        father[node1] = node2;
    }
    else{
        father[node2] = node1;
        depth[node1]++;
    }
}


int main()
{
    int n, m;
    cin >> n >> m;
    depth.assign(n + 1, 1);
    father.resize(n + 1);
    for(int i = 1; i <= n; i++)
        father[i] = i;
    for(int i = 0; i < m; i++){
        int c, x, y;
        cin >> c >> x >> y;
        if(c == 1)
            unire(x, y);
        else if(findrt(x) == findrt(y))
            cout << "DA" << '\n';
        else cout << "NU" << '\n';
    }
    return 0;
}