Cod sursa(job #2492215)

Utilizator IATI2019Iati Shumen IATI2019 Data 14 noiembrie 2019 10:08:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>

using namespace std;
int boss[100001];
int nr[100001];
int root(int x){
    if(boss[x] == x){
        return x;
    }
    boss[x] = root(boss[x]);
    return boss[x];
}
void unite(int a,int b){
    a = root(a);
    b = root(b);
    if(nr[a] > nr[b]){
        nr[a] += nr[b];
        boss[b] = a;
    }else{
        nr[b] += nr[a];
        boss[a] = b;
    }
}
int main()
{
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    int i,n,m;
    cin >> n >> m;
    for(i = 1;i <= n;i++){
        boss[i] = i;
        nr[i] = 1;
    }
    while(m--){
        int tip,a,b;
        cin >> tip >> a >> b;
        if(tip == 1){
            unite(root(a),root(b));
        }else{
            if(root(a) != root(b)){
                cout << "NU\n";
            }else{
                cout << "DA\n";
            }
        }
    }
    return 0;
}