Cod sursa(job #300531)

Utilizator belgun_adrianBelgun Dimitri Adrian belgun_adrian Data 7 aprilie 2009 14:58:04
Problema Trie Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.63 kb
// 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.