Cod sursa(job #3183851)

Utilizator thinkphpAdrian Statescu thinkphp Data 13 decembrie 2023 16:15:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <iostream>
#include <fstream>

#define FIN "disjoint.in"
#define FOUT "disjoint.out"

typedef unsigned int uint;
typedef unsigned long ulong;

using namespace std;

class UnionFind {

      public:
      //constructor of the class
      UnionFind(uint n):nElements(n), parent( new ulong[n+1] ), rank( new ulong[n+1] ) {

        for(int i = 1; i <= nElements; ++i) {

            parent[ i ] = i;

            rank[ i ] = 1;
        }

      };

      void unionSets(ulong x, ulong y) {

           ulong rootX = getRoot( x ),

                 rootY = getRoot( y );

           if(rank[ rootX ] > rank[ rootY ]) {

              parent[ rootY ] = rootX;

           } else if(rank[ rootX ] < rank[ rootY ]) {

              parent[ rootX ] = rootY;

           } else {

             parent[ rootY ] = rootX;

             rank[ rootY ]++;
           }
      }

      ulong sameSets(ulong x, ulong y) {

            ulong rootX = getRoot( x ),

                  rootY = getRoot( y );

            updatePathRoot(x, rootX);

            updatePathRoot(y, rootY);

            return rootX == rootY;
      }

      //destructor of the class
      ~UnionFind() {
        delete [] parent;
        delete [] rank;
      }

      private:
      uint nElements;
      ulong *parent,
            *rank;

      ulong getRoot( ulong node ) {

            ulong root = parent[ node ];

            while(root != parent[root]) {

                  root = parent[root];
            }

            return root;
      }

      void updatePathRoot(ulong node, ulong root) {

           if( root == parent[node] && node == root ) {

              return;
           }
      }

};

int main(int argc, char const *argv[]) {

  ulong numElements, numOps, type, x, y;

  ifstream fin( FIN );

  ofstream fout( FOUT );

  if(!fin) {
    cout<<"Error opening the file";
    return -1;
  }

  if(!fout) {
    cout<<"Error opening and writing the file";
    return -1;
  }

  fin>>numElements>>numOps;

  UnionFind forest( numElements );

  while( numOps-- ) {

       fin>>type>>x>>y;

       switch(type) {
         case 1:
         forest.unionSets(x, y);
         break;
         case 2:
         fout<< (forest.sameSets(x, y) ? "DA":"NU")<<"\n";
         break;
       }
  }
  return 0;
}