天天看點

二叉堆模闆

      二叉堆在各種競賽題目中通常都有涉及,主要是可以靈活地取出和插入,是一種線上的資料結構,對于幾種基本操作和原理一定要爛熟于心。

pascal模闆

放入操作 

procedure put(x:longint);
var
  fa,son,tmp:longint;
begin
  len:=len+1;
  heap[len]:=x;
  son:=len;
  while(son<>1)and(heap[son]<heap[son div 2]) do
  begin
    tmp:=heap[son div 2];
    heap[son div 2]:=heap[son];
    heap[son]:=tmp;
    son:=son div 2;
  end;
end;      
function get:longint;
var
  son,fa,tmp:longint;
  stop:boolean;
begin
  get:=heap[1];
  heap[1]:=heap[len];
  len:=len-1;
  fa:=1;
  stop:=false;
  while ((fa*2<=len)or(fa*2+1<=len))and(not stop) do
  begin
    if (fa*2+1>len)or (heap[fa*2]<heap[fa*2+1])
    then son:=fa*2
    else son:=fa*2+1;
  if heap[fa]>heap[son]
    then begin
      tmp:=heap[fa];
      heap[fa]:=heap[son];
      heap[son]:=tmp;
      fa:=son;
    end
    else stop:=true;
  end;
end;      

繼續閱讀