二叉堆模板

      二叉堆在各种竞赛题目中通常都有涉及,主要是可以灵活地取出和插入,是一种在线的数据结构,对于几种基本操作和原理一定要烂熟于心。

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;

       二叉堆一定要会用,可以飞快地做出来,理解原理,注意小细节,不要调用空单元,及时移动栈指针。

你可能感兴趣的:(模板)