Cod sursa(job #2942487)

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

using namespace std;

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

int n, m;

struct Node{
    Node* father;
    int index;
    int rang;
};
Node nodes[100000];

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

int main(){
    fin >> n;
    for(int i = 1; i <= n; i++){
        nodes[i].father = NULL;
        nodes[i].rang = 1;
        nodes[i].index = i;
    }

    fin >> m;

    int x, y, z;

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

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

    if(nodes[a].rang > nodes[b].rang){
        nodes[b].father = &nodes[a];
        nodes[a].rang += nodes[b].rang;
    }
    else{
        nodes[a].father = &nodes[b];
        nodes[b].rang += nodes[a].rang;
    }
}

int getFather(int x){
    int a = x;
    int b;

    while(nodes[x].father != NULL){
        x = nodes[x].father->index;
    }
    while(nodes[a].father != NULL){
        b = a;
        a = nodes[a].father->index;
        nodes[b].father = &nodes[x];
    }
    return x;
}