Cod sursa(job #2209870)

Utilizator TooHappyMarchitan Teodor TooHappy Data 4 iunie 2018 22:28:12
Problema Paduri de multimi disjuncte Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>
using namespace std;

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

vector< int > tata, h;

int GetParent(int u) {
    if(tata[u] == 0) {
        return u;
    }

    tata[u] = GetParent(tata[u]);
    return tata[u];
}

void Union(int u, int v) {
    int pU = GetParent(u);
    int pV = GetParent(v);

    if(h[pU] > h[pV]) {
        tata[pV] = pU;
    } else {
        tata[pU] = pV;

        if(h[pU] == h[pV]) {
            h[pV]++;
        }
    }
}

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);

    int n, m; in >> n >> m;

    tata.resize(n, 0); h.resize(n, 0);
    for(int i = 1; i <= m; ++i) {
        int op, x, y; in >> op >> x >> y;
        --x; --y;

        if(op == 1) {
            Union(x, y);
        } else {
            if(GetParent(x) == GetParent(y)) {
                out << "DA\n";
            } else {
                out << "NU\n";
            }
        }
    }

    in.close(); out.close();
      
    return 0;
}