Cod sursa(job #3226316)

Utilizator Toni07Stoica Victor Toni07 Data 20 aprilie 2024 21:35:25
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>

using namespace std;

const int Nmax = 100005;

int father[Nmax], n , m;

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

void Union(int x, int y) {
    int r_x = Find_root(x);
    int r_y = Find_root(y);
    if(r_x == r_y) {
        return;
    }
    if(father[r_x] < father[r_y]) {
        swap(r_x, r_y);
    }
    father[r_y] += father[r_x];
    father[r_x] = r_y;
}

int main() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    fin >> n >> m;
    for(int i = 1; i <= n; i++) {
        father[i] = -1;
    }
    while(m--) {
        int op, x, y;
        fin >> op >> x >> y;
        if(op == 1) {
            Union(x, y);
        }
        else {
            if(Find_root(x) == Find_root(y)) {
                fout << "DA\n";
            }
            else {
                fout << "NU\n";
            }
        }
    }
}