比赛 201001-line 评测结果 AWWWW
题目名称 可合并堆 最终得分 20
用户昵称 苏轼 运行时间 0.000 s
代码语言 Pascal 内存使用 0.00 MiB
提交时间 2010-01-18 21:27:56
显示代码纯文本
program uheap(input,output);

var
  n,com,i,j,a,b:integer;
  heap:array[0..100,-1..100]of integer;

procedure swap(var a,b:integer);
  var
    t:integer;
  begin
    t:=a;
    a:=b;
    b:=t;
  end;

procedure h_insert(a,num:integer);
  var
    i:integer;
  begin
    inc(heap[a,0]);
    i:=heap[a,0];
    heap[a,i]:=num;

    while (i>1)and(heap[a,i div 2]>heap[a,i]) do
    begin
      swap(heap[a,i],heap[a,i div 2]);

      i:=i div 2;
    end;
  end;

procedure min_heapify(a:integer);
  var
    l,r,min,i:integer;
  begin
    min:=1;
    i:=0;

    while min<>i do
    begin
      i:=min;
      l:=i*2;
      r:=i*2+1;

      if (l<=heap[a,0])and(heap[a,l]<heap[a,i]) then
        min:=l
      else
        min:=i;

      if (r<=heap[a,0])and(heap[a,r]<heap[a,min]) then
        min:=r;

      if min<>i then
        swap(heap[a,min],heap[a,i]);
    end;
  end;

function h_extractmin(a:integer):integer;
  begin
    dec(heap[a,0]);
    h_extractmin:=heap[a,1];
    heap[a,1]:=heap[a,i+1];

    min_heapify(a);
  end;

procedure h_union(a,b:integer);
  var
    i,j:integer;
  begin
    for i:=1 to heap[b,0] do
      h_insert(a,heap[b,i]);

    heap[b,0]:=0;
  end;

begin
  assign(input,'uheap.in');
  reset(input);

  assign(output,'uheap.out');
  rewrite(output);

  readln(n);

  for i:=1 to n do
  begin
    read(com);

    if com=1 then
    begin
      read(a);

      heap[a,-1]:=1;
      writeln(0);
    end
    else if com=2 then
    begin
      read(a,b);

      if heap[a,-1]=1 then
      begin
        h_insert(a,b);
        writeln(0);
      end else
        writeln('insert error!');
    end
    else if com=3 then
    begin
      read(a);

      if heap[a,0]=0 then
        writeln('extract error!')
      else
        writeln(h_extractmin(a));
    end
    else
    begin
      read(a,b);

      if (heap[a,-1]=0)or(heap[b,-1]=0) then
        writeln('union error!')
      else
      begin
        h_union(a,b);
        writeln(0);
      end;
    end;
  end;

  close(input);
  close(output);
end.