Cod sursa(job #2525965)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 18 ianuarie 2020 09:47:21
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 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];

        int aux;
        while (father[x]) {
            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, m;
    fin >> n >> m;

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

    fout.close();
    return 0;
}