Cod sursa(job #3166522)

Utilizator Allie28Radu Alesia Allie28 Data 8 noiembrie 2023 21:39:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <vector>
#include <queue>
#include <fstream>

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

const int LMAX = 100005;

int father[LMAX];

int findroot(int x) {
    if (father[x] < 0) {
        return x;
    }
    int root =  findroot(father[x]);
    father[x] = root;
    return root;
}

void unite(int x, int y) {
    int rx, ry;
    rx = findroot(x);
    ry = findroot(y);
    if (rx == ry) {
        return; ///sunt deja in aceeasi multime
    }
    if (father[ry] < father[rx]) {
        swap(ry, rx);
    }
    father[rx]+=father[ry];
    father[ry] =  rx;

}

int main() {
    int n, m;
    fin>>n>>m;
    for (int i = 0; i < n; i++) {
        father[i] = -1;
    }
    while (m--) {
        int t, a, b;
        fin>>t>>a>>b;
        if (t == 1) {
            unite(a, b);
        }
        else {
            if (findroot(a) == findroot(b)) {
                fout<<"DA";
            }
            else {
                fout<<"NU";
            }
            fout<<endl;
        }
    }

    fin.close();
    fout.close();

    return 0;
}