Cod sursa(job #1806189)

Utilizator M.AndreiMuntea Andrei Marius M.Andrei Data 14 noiembrie 2016 22:04:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream f{ "disjoint.in" };
ofstream q{ "disjoint.out" };

int find(const int& x, vector<int>& tata)
{
   int aux = x;
   while (aux != tata[aux])
   {
      aux = tata[aux];
   }
   //path compression;
   int pAux = x;
   int interm;
   while (pAux != tata[pAux])
   {
      interm = tata[pAux];
      tata[pAux] = aux;
      pAux = interm;
   }

   return aux;
}

void unionSet(int x, int y, vector<int>& tata, vector<int>& rang)
{
   int px, py;

   px = find(x, tata);
   py = find(y, tata);

   if (px == py) return;

   if (rang[px] >= rang[py])
   {
      tata[py] = px;
      if (rang[px] == rang[py]) rang[px]++;
   }
   else
   {
      tata[px] = py;
   }
}

int main()
{
   int n, m, op, y, x, px, py;
   f >> n >> m;
   vector<int> tata(n + 1, 0);
   vector<int> rang(n + 1, 0);

   for (int i = 0; i <= n; ++i) tata[i] = i, rang[i] = 0;

   while (m--)
   {
      f >> op >> x >> y;
      if (op == 1) unionSet(x, y, tata, rang);
      else {
         px = find(x, tata);
         py = find(y, tata);
         (px == py) ? q << "DA\n" : q << "NU\n";
      }
   }


   f.close();
   q.close();
   return 0;
}