Cod sursa(job #1896311)

Utilizator preda.andreiPreda Andrei preda.andrei Data 28 februarie 2017 16:45:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#include <vector>

using namespace std;

int Father(vector<int> &fathers, int x)
{
    if (fathers[x] == -1) {
        return x;
    }
    return (fathers[x] = Father(fathers, fathers[x]));
}

inline void Join(vector<int> &fathers, int x, int y)
{
    int fx = Father(fathers, x);
    int fy = Father(fathers, y);
    if (fx != fy) {
        fathers[fy] = fx;
    }
}

inline bool Connected(vector<int> &fathers, int x, int y)
{
    return Father(fathers, x) == Father(fathers, y);
}

int main()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    int n, m;
    fin >> n >> m;

    vector<int> fathers(n, -1);
    while (m--) {
        int r, x, y;
        fin >> r >> x >> y;

        if (r == 1) {
            Join(fathers, x - 1, y - 1);
        } else {
            fout << (Connected(fathers, x - 1, y - 1) ? "DA" : "NU") << "\n";
        }
    }

    return 0;
}