Cod sursa(job #2936007)

Utilizator ralucarRogoza Raluca ralucar Data 7 noiembrie 2022 21:19:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

vector<int>tata(100001);
vector<int>rang(100001);
int n, m, operatie, x, y;

int reprezentant(int nod){
    while(tata[nod] != nod){
        nod=tata[nod];
    }
    return nod;
}

void reuniune(int x, int y){
    int reprezentant_x = reprezentant(x), reprezentant_y = reprezentant(y);
    if(rang[reprezentant_x] < rang[reprezentant_y])
        tata[reprezentant_x] = reprezentant_y;
    else{
        tata[reprezentant_y] = reprezentant_x;
        if(rang[reprezentant_x] == rang[reprezentant_y])
            rang[reprezentant_y]++;
    }
}


int main() {
    fin>>n>>m;
    for(int i=1; i<=n; i++)
        tata[i]=i, rang[i]=1;
    for(int i=0; i<m; i++){
        fin>>operatie>>x>>y;
        if(operatie==1)
            reuniune(x, y);
        else{
            if(reprezentant(x) == reprezentant(y)) fout << "DA\n";
            else fout<<"NU\n";
        }
    }
    return 0;
}