Cod sursa(job #3283450)

Utilizator mircea_007Mircea Rebengiuc mircea_007 Data 9 martie 2025 16:35:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <stdio.h>
#include <assert.h>
#include <vector>

struct DSU {
  std::vector<int> dsu;
  DSU( int n ): dsu(n, -1) {}
  int find( int u ){
    if( dsu[u] < 0 )
      return u;
    return dsu[u] = find( dsu[u] );
  }

  bool same( int a, int b ) { return find( a ) == find( b ); }

  void unite( int a, int b ) {
    a = find( a );
    b = find( b );

    if( dsu[a] < dsu[b] ){
      dsu[a] += dsu[b];
      dsu[b] = a;
    }else{
      dsu[b] += dsu[a];
      dsu[a] = b;
    }
  }
};

int main() {
  FILE *fin = fopen( "disjoint.in", "r" );
  FILE *fout = fopen( "disjoint.out", "w" );

  int n, q;
  fscanf( fin, "%d%d", &n, &q );

  DSU zile(n);
  for( int i = 0; i < q; i++ ){
    int task, a, b;
    fscanf( fin, "%d%d%d", &task, &a, &b );

    if( task == 1 )
      zile.unite( --a, --b );
    else
      fputs( zile.same( --a, --b ) ? "DA\n" : "NU\n", fout );
  }

  fclose( fin );
  fclose( fout );
  return 0;
}