Cod sursa(job #1495266)

Utilizator diana97Diana Ghinea diana97 Data 2 octombrie 2015 20:36:38
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int NMAX = 100000;

int n, m;
int father[NMAX], height[NMAX];

void read() {
    f >> n >> m;
}

void init() {
    for (int i = 1; i <= n; i++) {
        father[i] = i;
        height[i] = 1;
    }
}

int root(int x) {
    if (father[x] == x) return x;
    father[x] = root(father[x]);
    return father[x];
}

void unite(int a, int b) {
    a = root(a);
    b = root(b);
    if (height[b] > height[a]) father[a] = b;
    else father[b] = a;
    if (height[a] == height[b]) height[a]++;
}

bool are_united(int a, int b) {
    return root(a) == root(b);
}

void solve() {
    int type, a, b;
    for (int i = 1; i <= m; i++) {
        f >> type >> a >> b;
        if (type == 1) unite(a, b);
        else {
            if (are_united(a, b)) g << "DA\n";
            else g << "NU\n";
        }
    }
}

int main() {
    read();
    init();
    solve();
    return 0;
}