IOIBIN - Các thùng nước

Tác giả: ll931110

Ngôn ngữ: Pascal

{$MODE DELPHI}
program ioibin2;
const
  input  = '';
  output = '';
  maxn = 10000;
var
  q: integer;
  fi,fo: text;
  p,rank: array[1..maxn] of integer;

procedure openfile;
begin
  assign(fi, input);
    reset(fi);

  assign(fo, output);
    rewrite(fo);
end;

function root(v: integer): integer;
begin
  if v <> p[v] then p[v] := root(p[v]);
  root := p[v];
end;

procedure union(r1,r2: integer);
begin
  if rank[r1] > rank[r2] then p[r2] := r1 else p[r1] := r2;
  if rank[r1] = rank[r2] then inc(rank[r2]);
end;

procedure solve;
var
  i,x,y,c,r1,r2: integer;
begin
  readln(fi, q);
  for i := 1 to maxn do
    begin
      p[i] := i;
      rank[i] := 0;
    end;

  for i := 1 to q do
    begin
      readln(fi, x, y, c);
      r1 := root(x);
      r2 := root(y);

      if (c = 1) and (r1 <> r2) then union(r1,r2)
      else if c = 2 then
        if r1 = r2 then writeln(fo, 1) else writeln(fo, 0);
    end;
end;

procedure closefile;
begin
  close(fo);
  close(fi);
end;

begin
  openfile;
  solve;
  closefile;
end.

Download