Cod sursa(job #3336238)

Utilizator tudorbeloiuLuka Modric tudorbeloiu Data 24 ianuarie 2026 14:06:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#include <vector>

using namespace std;

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

int n,m,p,x,y;
vector<int> tata;
vector<int> rang;

int getTata(int nod){
    if(tata[nod] != nod)
        tata[nod] = getTata(tata[nod]);
    return tata[nod];
}

void unirea_Romaniei(int x, int y){
    if(rang[x] < rang[y])
        tata[x] = y;
    else if(rang[x] > rang[y])
        tata[y] =x;
    else{
        tata[x] = y;
        rang[y]++;
    }
}

int main(){
    f >> n >> m;
    tata.resize(n+1);
    rang.resize(n+1, 0);
    for(int i=1; i<=n; i++)
        tata[i] = i;

    for(int i=1; i<=m; i++){
        f >> p >> x >> y;
        if(p == 1){
            int tataX = getTata(x);
            int tataY = getTata(y);
            if(tataX != tataY)
                unirea_Romaniei(tataX, tataY);
        }
        else if(p == 2){
            if(getTata(x) != getTata(y))
                g << "NU\n";
            else
                g << "DA\n";
        }
    }


    return 0;
}