Cod sursa(job #1985083)

Utilizator robertstrecheStreche Robert robertstreche Data 26 mai 2017 20:50:08
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>

#define NMAX 100000

using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

int prec[NMAX], number[NMAX];

inline int root(int node){

    while (node != prec[node])
        node = prec[node];

    return node;
}

inline void elem_union(int node_a, int node_b){

    int dad_a = root(node_a);
    int dad_b = root(node_b);

    if (number[dad_a] > number[dad_b]){
        prec[dad_b] = dad_a;
        number[dad_a] += number[dad_b];
    }
    else {
        prec[dad_a] = dad_b;
        number[dad_b] += number[dad_a];
    }

    return;
}

inline bool request(int node_a, int node_b){

    int dad_a = root(node_a);
    int dad_b = root(node_b);
    //cout << dad_a << " " << dad_b << '\n';

    return dad_a == dad_b;
}

int main()
{
    int n, m, op, x, y;

    f >> n >> m;

    for (int i = 1; i <= n; i++)
        prec[i] = i,
        number[i] = 1;
    //for (int i = 1; i <= n; i++)
    //    cout << prec[i] << " ";
    //cout << '\n';

    for (int i = 1; i <= m; i++){

        f >> op >> x >> y;
        //cout << x << " " << y << '\n';

        if (op == 1)
            elem_union(x, y);
        else
            g << (request(x, y) ? "DA" : "NU") << '\n';
    }

    f.close();
    g.close();

    return 0;
}