Cod sursa(job #3242768)

Utilizator UengineDavid Enachescu Uengine Data 14 septembrie 2024 01:10:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>

using namespace std;

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

const int N = 1e5;
int father[N + 5], depth[N + 5];

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

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

int main(){
    int n, m;
    cin >> n >> m;
    for (int i = 0; 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(find_root(x) != find_root(y))
                cout << "NU\n";
            else
                cout << "DA\n";
        }
    }
    return 0;
}