Cod sursa(job #2399105)

Utilizator isa_tudor_andreiAndrei Tudor isa_tudor_andrei Data 6 aprilie 2019 21:31:25
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <algorithm>
#include <vector>
#define NMAX 100000

using namespace std;

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

int root[NMAX + 1];
int rang[NMAX + 1];

int find_root( int x ) {
  int og = x;
  while( root[x] != -1 )
    x = root[x];
  while( root[og] != -1 ) {
    int oog = root[og];
    root[og] = x;
    og = oog;
  }
  return x;
}

void unite( int x, int y ) {
  if( rang[x] > rang[y] )
    root[y] = x;
  else
    root[x] = y;

  if( rang[x] == rang[y] )
    rang[y] ++;
}

int main() {
    int n, m, i, x, y, op;
    fin>>n>>m;
    for( i = 1; i <= n; i ++ )
      root[i] = -1, rang[i] = 1;
    for( i = 1; i <= m; i ++ ) {
      fin>>op>>x>>y;
      if( op == 1 ) {
        int rootx = find_root(x);
        int rooty = find_root(y);
        unite(rootx,rooty);
      }
      else {
        int rootx = find_root(x);
        int rooty = find_root(y);
        if( rootx == rooty )
          fout<<"DA"<<"\n";
        else
          fout<<"NU"<<"\n";
      }
    }
    return 0;
}