Cod sursa(job #2121315)

Utilizator justsomedudePalade Thomas-Emanuel justsomedude Data 3 februarie 2018 15:56:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include<iostream>
#include<fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int N, M, tip;
int t[100003], c[100003];


void Initializari()
{
   for (int i=1; i<=N; i++)
   { t[i] = 0;
     c[i] = 1;
   }
}

void Union(int x, int y)
{
  if (c[x] < c[y])
  {
      c[y] = c[y] + c[x];
      c[x] = 0;
      t[x] = y;
  }
  else
  {
      c[x] = c[x] + c[y];
      c[y] = 0;
      t[y] = x;
  }
}

int Find(int x)  /// returneaza taticul lui x, ala suprem
{
    int y,z;
    y = x;
    while (t[x] != 0)
       x = t[x];

    while (t[y] != 0)
    {
      z = t[y];
      t[y] = x;
      y = z;
    }
    return x;
}

int main ()
{
   fin >> N >> M;
   Initializari();
   int x, y;

   for (int i=1; i<=M; i++)
   {
      fin >> tip >> x >> y;
      if (tip == 1)
      {
         Union(Find(x), Find(y));
      }
      else
      {
         if (Find(x) == Find(y))
            fout << "DA\n";
         else
            fout << "NU\n";
      }
   }
  return 0;
}