Cod sursa(job #3268062)

Utilizator schema_227Stefan Nicola schema_227 Data 13 ianuarie 2025 16:33:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

vector<int> father;
vector<int> depth;

int FindRoot(int nod) {
    if(father[nod] == nod)
        return nod;
    return father[nod] = FindRoot(father[nod]);
}

void Union(int x, int y) {
    int r1 = FindRoot(x);
    int r2 = FindRoot(y);
    if(depth[r1] < depth[r2])
        father[r1] = r2;
    else if(depth[r1] > depth[r2])
        father[r2] = r1;
    else {
        father[r1] = r2;
        depth[r2]++;
    }
}

int main() {
    int N, M;
    in >> N >> M;

    father.resize(N+1);
    depth.resize(N+1);

    for(int i = 1; i <= N; i++) {
        father[i] = i;
        depth[i] = 0;
    }

    while(M--) {
        int op, x, y;
        in >> op >> x >> y;

        if(op == 1) {
            Union(x, y);
        } else {
            if(FindRoot(x) == FindRoot(y))
                out << "DA\n";
            else
                out << "NU\n";
        }
    }

    return 0;
}