Cod sursa(job #954366)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 28 mai 2013 23:38:30
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <cstdio>
#include <cassert>

#include <algorithm>
#include <vector>

using namespace std;

class DisjointSets {
  public:
    DisjointSets() {
        size = 0;
        father = vector<int>();
    }

    DisjointSets(const int size) {
        this->size = size;
        father = vector<int>(size, NIL);
        rank = vector<int>(size, 1);
    }

    int Find(const int x) {
        if (father[x] == NIL)
            return x;
        return father[x] = Find(father[x]);
    }

    bool Merge(int x, int y) {
        x = Find(x); y = Find(y);
        if (x == y)
            return false;
        if (rank[x] < rank[y])
            swap(x, y);
        father[y] = x;
        rank[x] = max(rank[x], rank[y] + 1);
        return true;
    }

  private:
    static const int NIL = -1;

    int size;
    vector<int> father, rank;
};

int main() {
    assert(freopen("disjoint.in", "r", stdin));
    assert(freopen("disjoint.out", "w", stdout));
    int N, M; assert(scanf("%d %d", &N, &M) == 2);
    DisjointSets sets = DisjointSets(N);
    for (; M > 0; --M) {
        int type, x, y;
        assert(scanf("%d %d %d", &type, &x, &y) == 3);
        --x; --y;
        if (type == 1)
            assert(sets.Merge(x, y));
        else
            printf("%s\n", (sets.Find(x) == sets.Find(y) ? "DA" : "NU"));
    }
    return 0;
}