Cod sursa(job #1784000)

Utilizator PaulStighiStiegelbauer Paul-Alexandru PaulStighi Data 19 octombrie 2016 17:49:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
using namespace std;

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

const int NMax = 100005;
int N,M;
int TT[NMax],R[NMax];

int Father(int Nod)
{
  while(Nod != TT[Nod])
    Nod = TT[Nod];
  return Nod;
}

void Unite(int x, int y)
{
  if(R[x] > R[y])
    TT[y] = x;
  if(R[y] > R[x])
    TT[x] = y;
  if(R[x] == R[y])
    {
      TT[x] = y;
      R[y]++;
    }
}

int main()
{
    fin>>N>>M;

    for(int i = 1; i <= N; ++i)
        TT[i] = i;

    while(M--)
    {
      int op,x,y;
      fin >> op >> x >> y;
      if(op == 1)
        Unite(Father(x),Father(y));
      if(op == 2)
        {
          if(Father(x) == Father(y))
            fout<<"DA\n";
          else
            fout<<"NU\n";
        }
    }
    return 0;
}