Cod sursa(job #305166)

Utilizator SprzlAbcdefg Sprzl Data 16 aprilie 2009 14:49:42
Problema Paduri de multimi disjuncte Scor 80
Compilator fpc Status done
Runda Arhiva educationala Marime 1.24 kb
program disjoint;
type  nod = ^articol;
      articol = record
              root:nod;
              l:integer;
            end;
var i,p,q,n,m:longint;
    c:byte;
    a:array [1..100000] of nod;
procedure union(var m1,m2:nod);
begin
  while m1^.root <> m1 do
  begin
    m1^.root:=m1^.root^.root;
    m1:=m1^.root;
  end;
  while m2^.root <> m2 do
  begin
    m2:=m2^.root;
    m2^.root:=m2^.root^.root;
  end;
  m1^.root:=m2;
  m2^.l:=m2^.l+m1^.l;
end;

procedure query(m1,m2:nod);
begin
  while m1^.root <> m1 do
  begin
    m1^.root:=m1^.root^.root;
    m1:=m1^.root;
  end;
  while m2^.root <> m2 do
  begin
    m2^.root:=m2^.root^.root;
    m2:=m2^.root;
  end;
  if m1 = m2 then
    writeln('DA')
  else
    writeln('NU');
end;

begin
  assign(input,'disjoint.in');
  assign(output,'disjoint.out');
  reset(input);
  rewrite(output);
  readln(n,m);
  for i:=1 to n do
  begin
    new(a[i]);
    a[i]^.root:=a[i];
    a[i]^.l:=1;
  end;

  for i:=1 to m do
  begin
    readln(c,p,q);
    if c =  1 then
    begin
      if a[p]^.l<a[q]^.l then
        union(a[p],a[q])
      else
        union(a[q],a[p]);
    end
    else
      query(a[p],a[q]);
  end;

  close(input);
  close(output);

end.