Cod sursa(job #3255309)

Utilizator raizoSoare Antonio raizo Data 10 noiembrie 2024 11:40:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>
using namespace std;

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

class DisjointSet {
private:
    std::vector<int> set;
public:
    DisjointSet(int size) : set{ vector<int>(size, -1) } {}

    int Find(int x) {
        while (set[x] >= 0) {
            int parent = set[x];
            if (set[parent] >= 0) {
                set[x] = set[parent];
            }
            x = parent;
        }
        return x;
    }

    void Union(int x, int y) {
        int rootx = Find(x);
        int rooty = Find(y);

        if (set[rootx] < set[rooty]) { // add y to x
            set[rootx] += set[rooty];
            set[rooty] = rootx;
        }
        else { // add x to y
            set[rooty] += set[rootx];
            set[rootx] = rooty;
        }
    }

    int size(int x) {
        x = Find(x);
        return -set[x];
    }

};

int main()
{
    int n, m, op, x, y;
    cin >> n >> m;
    DisjointSet s(n+1);
    for (int i = 0; i < m; i++) {
        cin >> op >> x >> y;
        if (op == 1) {
            s.Union(x, y);
        }
        else {
            if (s.Find(x) == s.Find(y)) {
                cout << "DA\n";
            }
            else {
                cout << "NU\n";
            }
        }
    }
}