Cod sursa(job #1110221)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 17 februarie 2014 21:30:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>

using namespace std;

class DisjointSets {
  public:
    static const int NIL = -1;

    DisjointSets(const int size = 0):
      father(vector<int>(size, NIL)),
      rank(vector<int>(size, 0)) {}

    int Size() const {
        return int(father.size());
    }

    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:
    vector<int> father, rank;
};

int main() {
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    int n, q;
    cin >> n >> q;
    DisjointSets sets = DisjointSets(n);
    for (; q > 0; --q) {
        int type;
        cin >> type;
        if (type == 1) {
            int x, y;
            cin >> x >> y;
            sets.Merge(--x, --y);
        } else {
            int x, y;
            cin >> x >> y;
            if (sets.Find(--x) == sets.Find(--y))
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }
    cin.close();
    cout.close();
    return 0;
}