Cod sursa(job #581397)

Utilizator dutzu93Vlad Vedinas dutzu93 Data 14 aprilie 2011 08:52:43
Problema Heapuri Scor 30
Compilator fpc Status done
Runda Arhiva educationala Marime 1.67 kb
const
	nmax=200000;
type
	heap=array[1..nmax] of longint;
var
	h,v,pos:heap;
	n,i,w,ww,nh,m:longint;

function father(nod:longint):longint; begin father:=nod div 2; end;
function left_son(nod:longint):longint; begin left_son:=2*nod; end;
function right_son(nod:longint):longint; begin right_son:=2*nod+1; end;
procedure swap(var a,b:longint); begin a:=a+b; b:=a-b; a:=a-b; end;
	
procedure percolate(k:longint);
	var
		key,keyp:longint;
	begin
		key:=h[k];
		keyp:=k;
		while (k>1) and (v[key] < v[h[father(k)]]) do begin
			pos[h[father(k)]]:=k;
			h[k]:=h[father(k)];
			k:=father(k);
		end;
		h[k]:=key;
		pos[keyp]:=k;
	end;
	
procedure sift(k:longint);
	var
		son:longint;
	begin
		repeat
			son:=0;
			if left_son(k)<=nh then begin
				son:=left_son(k);
				if (right_son(k)<=nh) and (v[h[son]] > v[h[right_son(k)]]) then son:=right_son(k);
				if v[h[son]] > v[h[k]] then son:=0;
			end;
			if son>0 then begin
				swap(pos[h[son]],pos[h[k]]);
				swap(h[son],h[k]);
				k:=son;
			end;
		until son=0;
		
	end;

procedure insert(key:longint);
	begin
		inc(n);inc(nh);
		v[n]:=key;
		h[nh]:=n;
		pos[n]:=nh;
		percolate(nh);
	end;

procedure cut(k:longint);
	begin
        pos[h[nh]]:=k;
		h[k]:=h[nh];
        k:=pos[h[k]];
		dec(nh);
		if (k>1) and (v[h[k]] < v[h[father(k)]]) then percolate(k) else sift(k);
	end;
	
begin
	assign(input,'heapuri.in');reset(input);
	assign(output,'heapuri.out');rewrite(output);
	nh:=0;
	n:=0;
	readln(m);
	for i:=1 to m do begin
		read(w);
		case w of
			1:begin read(ww); insert(ww); end;
			2:begin read(ww); cut(pos[ww]); end;
			3:begin writeln(v[h[1]]); end;
		end;
	end;

end.