Cod sursa(job #3252787)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 31 octombrie 2024 10:27:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const int NMAX = 1e5;

struct DSU {
    vector<int> h, p;
    DSU(int n) {
        h.resize(n + 1);
        p.resize(n + 1);
        for(int i = 1; i <= n; i++) {
            h[i] = 1;
            p[i] = i;
        }
    }

    int Find(int x) {
        int r = x;
        while(r != p[r]) {
            r = p[r];
        }
        int y = x;
        while(y != r) {
            int t = p[y];
            p[y] = r;
            y = t;
        }
        return r;
    }

    void Union(int x, int y) {
        x = Find(x);
        y = Find(y);
        if(x != y) {
            if(h[x] < h[y]) {
                p[x] = y;
            } else {
                if(h[y] < h[x]) {
                    p[y] = x;
                } else {
                    p[y] = x;//p[x] = y si h[y]++;
                    h[x]++;
                }
            }
        }
    }

};

int main()
{
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    int n, m;
    f >> n >> m;
    DSU d(n);
    for(int i = 1; i <= m; i++) {
        int op, x, y;
        f >> op >> x >> y;
        if(op == 1) {
            d.Union(x, y);
        } else {
            if(d.Find(x) == d.Find(y)) {
                g << "DA\n";
            } else {
                g << "NU\n";
            }
        }
    }
    return 0;
}