Cod sursa(job #1170632)

Utilizator wollyFusy Wool wolly Data 13 aprilie 2014 22:54:19
Problema Heapuri Scor 10
Compilator fpc Status done
Runda Arhiva educationala Marime 1.6 kb
type tab=array[0..200100] of longint;
	heap=array[0..200100] of longint;
var a,b:text;
	num,op,n,i,j:longint;
	h:heap;
	t:tab;
	
procedure add(num,p:longint);
var a,b:longint;
begin
	t[p]:=p;
	h[p]:=num;
	while (h[p div 2]>h[p]) do
		begin
		a:=h[p div 2];
		b:=t[p div 2];
		h[p div 2]:=h[p];
		t[p div 2]:=t[p];
		h[p]:=a;
		t[p]:=b;
		p:=p div 2;
		end;
end;	
	
procedure del(p,f:longint);
var a,b,i:longint;
begin
	i:=1;
	while t[i]<>p do i:=i+1;
	p:=i;
	{writeln(p,'x');}
	h[p]:=h[f];
	h[f]:=0;
	t[p]:=t[f];
	j:=j-1;
	
	{for i:=1 to n do write(h[i],' ');
	writeln;}
	
	
	if (p>1) and (h[p]<h[p div 2]) then
		while (h[p div 2]>h[p]) do
			begin
			a:=h[p div 2];
			b:=t[p div 2];
			h[p div 2]:=h[p];
			t[p div 2]:=t[p];
			h[p]:=a;
			t[p]:=b;
			p:=p div 2;
			end else
		begin
		while (2*p<=j) do
			if ((h[2*p]<h[2*p+1]) and (h[2*p]>0)) or (h[2*p+1]=0) then
				begin
				a:=h[p];
				b:=t[p];
				h[p]:=h[2*p];
				t[p]:=t[2*p];
				h[2*p]:=a;
				t[2*p]:=b;
				p:=2*p;
				end else 
			if ((h[2*p]>=h[2*p+1]) and (h[2*p+1]>0)) or (h[2*p]=0) then
				begin
				a:=h[p];
				b:=t[p];
				h[p]:=h[2*p+1];
				t[p]:=t[2*p+1];
				h[2*p+1]:=a;
				t[2*p+1]:=b;
				p:=2*p+1;
				end;
		end;
	{for i:=1 to n do write(h[i],' ');
	writeln;}
end;	
	
begin
assign(a,'heapuri.in'); reset(a);
assign(b,'heapuri.out'); rewrite(b);
readln(a,n);
for i:=1 to n do
	begin
	read(a,op);
	case op of
		1:begin j:=j+1; read(a,num); add(num,j); end;
		2:begin read(a,num); del(num,j); end;
		3:writeln(b,h[1]);
	end;
	end;
close(a);
close(b);
end.