Cod sursa(job #883191)

Utilizator andrei_toaderToader Andrei Sorin andrei_toader Data 19 februarie 2013 20:09:28
Problema Paduri de multimi disjuncte Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.22 kb
program multimi;
var f,g:text;
    n,m,i,cd,x,y:longint;
    t:array[1..100020] of longint;
    rg:array[1..100020] of longint;
    bufin,bufout:array[1..65000] of byte;

function gaseste (x:longint):longint;
begin
 {merg in sus pe arbore pana gasesc un nod cu t[i]=i}
 while t[x]<>x do
 begin
  x:=t[x];
 end;
 gaseste:=x;
end;

procedure uneste (x,y:longint);
begin
 {unesc multimea cu rang mai mic de cea cu rang mai mare}
 if rg[x]>rg[y] then t[y]:=x
 else t[x]:=y;
 {in caz ca rangurile erau egale cresc rangul noii multimi cu 1}
 if rg[x]=rg[y] then inc(rg[y]);
end;

begin
 assign (f,'disjoint.in'); reset (F);
 assign (g,'disjoint.out'); rewrite (G);
 settextbuf (f,bufin); settextbuf (g,bufout);
 readln (f,n,m);
 for i:=1 to n do
 begin
  t[i]:=i; rg[i]:=1; {initial rangul fiecarui arbore este 1}
 end;
 for i:=1 to m do
 begin
  readln (f,cd,x,y);
  if cd=2 then
  begin
   if gaseste(x)=gaseste(y) then   {verific daca radacina arborilor in care se afla x si y este egala}
    writeln (g,'DA')

   else
    writeln (G,'NU');
  end
  else
  begin
   uneste(gaseste(x), gaseste(y)); {unesc radacinile corespunzatoare multimilor nodurilor x si y}
  end;
 end;
 close (f); close (g);
end.