Cod sursa(job #1604321)

Utilizator Vali_DeaconuVali Deaconu Vali_Deaconu Data 18 februarie 2016 09:44:12
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
# include <fstream>
# define MAXN 100010

using namespace std;

int t[MAXN], r[MAXN];
int n, m;

int cauta(int nod1) {
    int R, nod2;

    for (R = nod1; t[R] != R; R = t[R]) ;

    while (t[nod1] != nod1) {
        nod2 = t[nod1];
        t[nod1] = R;
        nod1 = nod2;
    }

    return R;
}

void lipeste(int nod1, int nod2) {
    if (r[nod1] > r[nod2])
        t[nod2] = nod1;
    else
        t[nod1] = nod2;

    if (r[nod1] == r[nod2])
        ++r[nod2];
}

int main() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    int x, y, p;
    fin >> n >> m;
    for (int i=1; i<=n; ++i) {
        r[i] = i;
        t[i] = i;
    }
    for (int i=1; i<=m; ++i) {
        fin >> p >> x >> y;
        if (p == 2) {
            if (cauta(x) == cauta(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        } else if (cauta(x) == cauta(y))
            lipeste(cauta(x), cauta(y));
    }

    fin.close();
    fout.close();
    return 0;
}