Cod sursa(job #2274584)

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

class APM {

private:
    vector <int> a[NMAX];
    int root[NMAX];

    void combine(int x, int y) {
        root[x] = y;
        a[y].push_back(x);
        for (int i = a[x].size() - 1; i >= 0; --i) {
            int p = a[x][i];
            root[p] = y;
            a[y].push_back(p);
            a[x].pop_back();
        }
    }


public:

    APM(int n) {
        for (int i = 1; i <= n; ++i ) {
            a[i].clear();
            root[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 (t1 < 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;
}