堆
来源:互联网 发布:斯蒂芬库里 知乎 编辑:程序博客网 时间:2024/05/23 17:43
堆
小根堆
<span style="font-size:24px;">const maxn=1000;var n,l,i,temp:longint; a:array[0..maxn] of longint; procedure put(x:longint);var son,temp:longint;begin inc(l); a[l]:=x; son:=l; while (son<>1) and (a[son div 2]>a[son]) do begin temp:=a[son]; a[son]:=a[son div 2]; a[son div 2]:=temp; son:=son div 2; end;end; function get:longint;var fa,son,temp:longint; stop:boolean;begin get:=a[1]; a[1]:=a[l]; dec(l); fa:=1; stop:=false; while (fa*2<=l) and (not stop) do begin if (fa*2+1>l) or (a[fa*2]<a[fa*2+1])</span><span style="font-size:32px;color:#ff0000;">//两个判断一定不能反!</span><span style="font-size:24px;"> then son:=fa*2 else son:=fa*2+1; if a[fa]>a[son] then begin temp:=a[fa];</span><pre name="code" class="delphi">
大根堆
<span style="font-size:32px;">const maxn=1000;var n,l,i,temp:longint; a:array[0..maxn] of longint; procedure put(x:longint);var son,temp:longint;begin inc(l); a[l]:=x; son:=l; while (son<>1) and (a[son div 2]<a[son]) do begin temp:=a[son]; a[son]:=a[son div 2]; a[son div 2]:=temp; son:=son div 2; end;end; function get:longint;var fa,son,temp:longint; stop:boolean;begin get:=a[1]; a[1]:=a[l]; dec(l); fa:=1; stop:=false; while (fa*2<=l) and (not stop) do begin if (fa*2+1>l) or (a[fa*2]>a[fa*2+1])<span style="color: rgb(255, 0, 0); ">//两个判断一定不能反!</span> then son:=fa*2 else son:=fa*2+1; if a[fa]<a[son] then begin temp:=a[fa]; a[fa]:=a[son]; a[son]:=temp; fa:=son; end else stop:=true; end;end;begin read(n); l:=0; for i:=1 to n do begin read(temp); put(temp); end; for i:=1 to n do writeln(get);end.</span>
1 0