Cod sursa(job #2299589)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 9 decembrie 2018 19:12:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

int dad[MAXN], high[MAXN];

int getroot(int nod){
    int root = nod;
    while(root != dad[root])
        root = dad[root];
    int cp;
    while(nod != root){
        cp = nod;
        nod = dad[nod];
        dad[cp] = root;
    }
    return nod;
}

int main()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= n; ++i){
        dad[i] = i;
        high[i] = 1;
    }
    while(m){
        int op, x, y;
        fin >> op >> x >> y;
        if(op == 1){
            int rx = getroot(x), ry = getroot(y);
            if(high[rx] > high[ry])
                dad[ry] = rx;
            else if(high[rx] < high[ry])
                dad[rx] = ry;
            else{
                dad[rx] = ry;
                high[rx]++;
            }
        }
        else{
            if(getroot(x) == getroot(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
        m--;
    }
    return 0;
}