Cod sursa(job #2942510)

Utilizator imbirbyzBirbyz imbirbyz Data 19 noiembrie 2022 19:27:25
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

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

int n, m;
vector <int> father;

int getFather(int x);
void pairUp(int x, int y);

int main(){
    fin >> n >> m;
    
    father.resize(n+1, 0);

    // we consider that the predecessor of each node is the node itself
    // thinking of each node as a separate conex component
    for(int i = 1; i <= n; i++){
        father[i] = i;
    }

    for(int i = 0; i < m; i++){
        int x, y, z;
        fin >> x >> y >> z;
        if(x == 1){
            pairUp(y, z);
        }
        else{
            if(getFather(y) != getFather(z)){
                fout << "NU" << endl;
            }
            else{
                fout << "DA" << endl;
            }
        }
    }
}

int getFather(int x){
    // if the current node is the 'father' then return
    if(father[x] == x){
        return x;
    }

    //otherwise, keep looking for the 'father' of the current
    //conex component
    father[x] = getFather(father[x]);
    return father[x];
}

void pairUp(int x, int y){
    int a = getFather(x);
    int b = getFather(y);

    father[a] = b;
}