Pagini recente » Cod sursa (job #118542) | Cod sursa (job #2130112) | Cod sursa (job #999760) | Cod sursa (job #1146157) | Cod sursa (job #300531)
Cod sursa(job #300531)
// Arhiva educationala - Trie
type
adresa = ^trie;
trie = record val, nrf : integer; c : array['a'..'z'] of adresa; end;
var
tr : adresa;
c1, c2 : char;
s : string;
f, g : text;
procedure add (t : adresa; s : string);
begin
if (s = '') then
begin
inc (t^.val); exit;
end;
if (t^.c[s[1]] = nil) then
begin
new (t^.c[s[1]]);
fillchar (t^.c[s[1]]^, sizeof (t^.c[s[1]]^), 0);
inc (t^.nrf);
end;
add (t^.c[s[1]], copy (s, 2, length(s)-1));
end;
function delete (t : adresa; s : string) : byte;
begin
if (s = '') then
dec (t^.val)
else
if (delete (t^.c[s[1]], copy (s, 2, length(s)-1)) = 1) then
begin
t^.c[s[1]] := nil;
dec (t^.nrf);
end;
if (t^.val = 0) and (t^.nrf = 0) and (t <> tr) then
begin
dispose (t);
delete := 1; exit;
end;
delete := 0;
end;
function query (t : adresa; s : string) : longint;
begin
if (s = '') then
begin
query := t^.val; exit;
end;
if (t^.c[s[1]] <> nil) then
begin
query := query (t^.c[s[1]], copy (s, 2, length(s)-1)); exit;
end;
query := 0;
end;
function prefi (t : adresa; s : string; k : longint) : longint;
begin
if (s = '') or (t^.c[s[1]] = nil) then
begin
prefi := k; exit;
end;
prefi := prefi (t^.c[s[1]], copy (s, 2, length(s)-1), k+1);
end;
begin
assign (f, 'trie.in'); assign (g, 'trie.out');
reset (f); rewrite (g);
new (tr);
fillchar (tr^, sizeof (tr^), 0);
while not eof(f) do
begin
readln(f, c1, c2, s);
case c1 of
'0' : add (tr, s);
'1' : delete (tr, s);
'2' : writeln (g, query (tr, s));
'3' : writeln (g, prefi (tr, s, 0));
end;
end;
close (f); close (g);
end.