Cod sursa(job #3187979)

Utilizator UengineDavid Enachescu Uengine Data 31 decembrie 2023 18:37:37
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int N = 1e5;
vector <int> depth, father;

int find_root(int nod){
    if(nod == father[nod])
        return nod;
    return father[nod] = find_root(father[nod]);
}

void unite(int nod1, int nod2){
    nod1 = find_root(nod1);
    nod2 = find_root(nod2);
    if(depth[nod1] < depth[nod2])
        father[nod1] = nod2;
    else if(depth[nod1] > depth[nod2])
        father[nod2] = nod1;
    else{
        father[nod1] = nod2;
        depth[nod2]++;
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    father.resize(n + 1);
    depth.assign(n + 1, 1);
    for (int i = 1; i <= n; ++i)
        father[i] = i;
    for (int i = 0; i < m; ++i) {
        int cer, nod1, nod2;
        cin >> cer >> nod1 >> nod2;
        if(cer == 1)
            unite(nod1, nod2);
        else if(find_root(nod1) == find_root(nod2))
            cout << "DA\n";
        else cout << "NU\n";
    }
    return 0;
}