Cod sursa(job #3163576)

Utilizator PescarusTanislav Luca Andrei Pescarus Data 31 octombrie 2023 17:21:30
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <algorithm>

using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
const int nmax = 100005;

int father[nmax];
int n, m;
int gaseste_tatal(int x){
    if(father[x] < 0){
      return x;
    }
    int root = gaseste_tatal(father[x]);
    father[x] = root;
    return root;
}
void unite(int x, int y){
    int r_x = gaseste_tatal(x);
    int r_y = gaseste_tatal(y);
    if(r_x == r_y){
      return;
    }
    if(father[r_x] < father[r_y]){
      swap(r_x, r_y);
    }
    father[r_y] += father[r_x];
    father[r_x] = r_y;

}
int main(){
    f >> n >> m;
    for(int i = 1; i <= n; i++){
      father[i] = -1;
    }
    for(int i = 1; i <= m; i++){
      int x, y, z;
      f >> z >> x >> y;
      if(z == 1){
          unite(x, y);
      }
      else if(z == 2){
        if(gaseste_tatal(x) == gaseste_tatal(y)){
          g << "DA" << '\n';
        }
        else{
          g << "NU" << '\n';
        }
      }
    }

}