Cod sursa(job #2274588)

Utilizator mihaicivMihai Vlad mihaiciv Data 2 noiembrie 2018 09:38:41
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 100001
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

class APM {

private:
    int root[NMAX];
    int last[NMAX]; /// ultimul element din grup
    int next[NMAX]; /// urmatorul element din grup
    int groupSize[NMAX]; /// nr de elemente din grup

    void resetRoot(int x, int y, int l) {
        root[x] = y;
        if (x != l) {
            resetRoot(next[x], y, l);
        }
    }

    void combine(int x, int y) {

        int l = last[y];
        next[l] = x;
        last[y] = last[x];
        resetRoot(x, y, last[x]);

    }


public:

    APM(int n) {
        for (int i = 1; i <= n; ++i ) {
            groupSize[i] = 1;
            root[i] = i;
            next[i] = 0;
            last[i] = i;
        }
    }

    int getRoot(int x) { return root[x]; }

    void groupRoots(int x, int y) {

        int t1 = getRoot(x);
        int t2 = getRoot(y);

        /// se garanteaza ca t1 != t2

        if (groupSize[t1] < groupSize[t2]) {
            combine(t1, t2);
        } else {
            combine(t2, t1);
        }

    }


};

int main() {


    int n, m;


    f >> n >> m;
    APM a(n);
    for (int i = 0; i < m; ++i) {

        int type, x, y;
        f >> type >> x >> y;
        if (type == 1) {

            a.groupRoots(x, y);


        } else {

            int t1 = a.getRoot(x);
            int t2 = a.getRoot(y);

            if (t1 != t2) {
                g << "NU\n";
            } else {
                g << "DA\n";
            }

        }
    }

    return 0;
}