Cod sursa(job #308594)

Utilizator mlazariLazari Mihai mlazari Data 27 aprilie 2009 21:41:40
Problema Trie Scor 20
Compilator fpc Status done
Runda Arhiva educationala Marime 1.78 kb
Program Trie;
type PNod=^Nod;
     Nod=record
       count,nf : byte;
       f : array['a'..'z'] of PNod;
     end;
     Cuvant=string[20];
var Intrare,Iesire : text;
    P : PNod;

procedure DeschideFisiere;
begin
  assign(Intrare,'trie.in');
  assign(Iesire,'trie.out');
  reset(Intrare);
  rewrite(Iesire);
end;

function nou : PNod;
var q : PNod;
    ch : char;
begin
  new(q);
  q^.count:=0;
  q^.nf:=0;
  for ch:='a' to 'z' do q^.f[ch]:=nil;
  nou:=q;
end;

procedure modifica(cuv : Cuvant; k : shortint);
var x : PNod;
    i,l : byte;
begin
  x:=P;
  l:=length(cuv);
  for i:=1 to l do begin
    x^.nf:=x^.nf+k;
    if x^.f[cuv[i]]=nil then x^.f[cuv[i]]:=nou;
    if (x^.f[cuv[i]]^.nf=-k) or (i=l) and (x^.f[cuv[i]]^.count=-k) then begin
      x^.f[cuv[i]]:=nil;
      exit;
    end;
    x:=x^.f[cuv[i]];
  end;
  x^.count:=x^.count+k;
end;

function nrcuv(cuv : Cuvant) : longint;
var x : PNod;
    i : byte;
begin
  x:=P;
  for i:=1 to length(cuv) do
   if x<>nil then x:=x^.f[cuv[i]] else break;
  if x<>nil then nrcuv:=x^.count else nrcuv:=0;
end;

function lungpref(cuv : Cuvant) : byte;
var x : PNod;
    i,l : byte;
begin
  l:=0;
  x:=P;
  for i:=1 to length(cuv) do begin
    x:=x^.f[cuv[i]];
    if x<>nil then l:=i else break;
  end;
  lungpref:=l;
end;

procedure Proceseaza;
var cuv : Cuvant;
    op : byte;
    sp : char;
begin
  P:=nou;
  while not eof(Intrare) do begin
    readln(Intrare,op,sp,cuv);
    case op of
      0: modifica(cuv,1);
      1: modifica(cuv,-1);
      2: writeln(Iesire,nrcuv(cuv));
      3: writeln(Iesire,lungpref(cuv));
    end;
  end;
end;

procedure InchideFisiere;
begin
  close(Intrare);
  close(Iesire);
end;

begin
  DeschideFisiere;
  Proceseaza;
  InchideFisiere;
end.