Cod sursa(job #2572726)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 5 martie 2020 13:59:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda OJI 2020 Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;

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

class Forest {
  private:
    vector<int> height;
    vector<int> father;

  public:
    Forest(int n) :
        height(n + 1), father(n + 1) { }

    int find(int x) {
        int root = x;
        while (father[root])
            root = father[root];

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

    void unite(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX == rootY)
            return;

        if (height[rootX] < height[rootY])
            father[rootX] = rootY;
        else {
            father[rootY] = rootX;
            if (height[rootX] == height[rootY])
                height[rootX]++;
        }
    }
};

int main() {
    int n, q; fin >> n >> q;
    Forest forest(n);
    for (int i = 0; i < q; i++) {
        int t, x, y; fin >> t >> x >> y;
        if (t == 1)
            forest.unite(x, y);
        else
            fout << (forest.find(x) == forest.find(y) ? "DA\n" : "NU\n");
    }

    fout.close();
    return 0;
}