Pagini recente » Cod sursa (job #43987) | Cod sursa (job #2113044) | Cod sursa (job #2218484) | Cod sursa (job #2430891) | Cod sursa (job #946114)
Cod sursa(job #946114)
program binary_search_tries;
type arbore=^celula;
celula=record
info:longint;
p,left,right:arbore;
end;
var t,r:arbore;
n,w,z:longint;
op:byte;
bufin,bufout:array[1..100000]of byte;
function search(t:arbore;x:longint):arbore;
var r:arbore;
begin
r:=t;
while (r<>nil) and (r^.info<>x) do
begin
if x<r^.info then r:=r^.left
else r:=r^.right;
end;
search:=r;
end;
function search2(t:arbore;x:longint):byte;
var r:arbore;
begin
r:=t;
while (r<>nil) and (r^.info<>x) do
begin
if x<r^.info then r:=r^.left
else r:=r^.right;
end;
if r=nil then search2:=0 else search2:=1;
end;
function min(t:arbore):arbore;
var r:arbore;
begin
r:=t;
while r^.left<>nil do r:=r^.left;
min:=r;
end;
function max(t:arbore):arbore;
var r:arbore;
begin
r:=t;
while r^.right<>nil do r:=r^.right;
max:=r;
end;
function succesor(t:arbore):arbore;
var r:arbore;
begin
if t^.right<>nil then succesor:=min(t^.right)
else begin
r:=t;
while (r^.p<>nil) and (r^.p^.right=r) do r:=r^.p;
succesor:=r^.p;
end;
end;
function predecesor(t:arbore):arbore;
var r:arbore;
begin
if t^.left<>nil then predecesor:=max(t^.left)
else begin
r:=t;
while (r^.p<>nil) and (r^.p^.left=r) do r:=r^.p;
predecesor:=r^.p;
end;
end;
procedure insert(t,x:arbore);
var r,y:arbore;
begin
r:=t;y:=t^.p;
while (r<>nil)and(r^.info<>x^.info) do
begin
y:=r;
if x^.info<r^.info then r:=r^.left
else r:=r^.right;
end;
if r=nil then
if x^.info<y^.info then begin x^.p:=y; y^.left:=x; end
else begin x^.p:=y; y^.right:=x; end;
end;
procedure delete(t,z:arbore);
var y,x:arbore;
begin
if (z^.left=nil)or(z^.right=nil) then y:=z
else y:=succesor(z);
if y^.left=nil then x:=y^.right
else x:=y^.left;
if x<>nil then x^.p:=y^.p;
if y^.p=nil then t:=x
else if y=y^.p^.left then y^.p^.left:=x
else y^.p^.right:=x;
if y<>z then z^.info:=y^.info;
end;
begin
assign(input,'hashuri.in');
reset(input);
settextbuf(input,bufin);
assign(output,'hashuri.out');
rewrite(output);
settextbuf(output,bufout);
readln(n);
repeat
readln(op,w);
if op=3 then writeln(0);
until op=1;
new(t);
t^.info:=z;
while not eof do
begin
readln(op,w);
case op of
1: begin new(r);r^.info:=w;if t= nil then t:=r else insert(t,r);end;
2: begin r:=search(t,w); if r<>nil then delete(t,r); end;
3: writeln(search2(t,w));
end;
end;
close(input);close(output);
end.