Cod sursa(job #411677)

Utilizator hungntnktpHungntnktp hungntnktp Data 5 martie 2010 03:13:07
Problema Trie Scor 45
Compilator fpc Status done
Runda Arhiva educationala Marime 2.77 kb
{FP}
{$M 64000000,0}
{$MODE OBJFPC}
{$IFDEF ANHDQ}
  {$INLINE OFF}
  {$H-,I+,Q+,R+,S+}
{$ELSE}
  {$INLINE ON}
  {$H+,I-,Q-,R-,S-}
{$ENDIF}

// Result:
program trie_AnhDQ;

const
  FI_NAME = 'trie.in';
  FO_NAME = 'trie.out';
  MaxN    = 200000;

type
  TNode = record
            midCount, endCount: LongInt;
            Next              : array['a'..'z'] of LongInt;
          end;

var
  k, len, cnt, res: LongInt;
  w               : string;
  T               : array[0..MaxN] of TNode;
(*------------------------------*)
  procedure ReadQuery(); inline;
  begin
    read(k);
    SeekEOLn();
    ReadLn(w);
    len := Length(w);
  end;
(*------------------------------*)
  procedure Add(); inline;
  var node, i: LongInt;
  begin
    node := 0; i := 1;
    while i <= len do
    begin
      if T[node].Next[w[i]] = 0 then
      begin
        Inc(cnt);
        T[node].Next[w[i]] := cnt;
      end;
      Inc(T[T[node].Next[w[i]]].midCount);
      if i = len then Inc(T[T[node].Next[w[i]]].endCount);
      node := T[node].Next[w[i]];
      Inc(i);
    end;
  end;
(*------------------------------*)
  procedure Del(); inline;
  var node, i: LongInt;
  begin
    node := 0; i := 1;
    while i <= len do
    begin
      if T[node].Next[w[i]] = 0 then exit;
      Dec(T[T[node].Next[w[i]]].midCount);
      if i = len then Dec(T[T[node].Next[w[i]]].endCount);
      node := T[node].Next[w[i]];
      Inc(i);
    end;
  end;
(*------------------------------*)
  procedure Count(); inline;
  var node, i: LongInt;
  begin
    node := 0; i := 1;
    while i <= len do
    begin
      if (T[node].Next[w[i]] = 0) or (T[T[node].Next[w[i]]].midCount = 0) then
        exit;
      if i = len then
      begin
        res := T[T[node].Next[w[i]]].endCount;
        exit;
      end;
      node := T[node].Next[w[i]];
      Inc(i);
    end;
  end;
(*------------------------------*)
  procedure Count2(); inline;
  var node, i: LongInt;
  begin
    node := 0; i := 1;
    while i <= len do
    begin
      if (T[node].Next[w[i]] = 0) or (T[T[node].Next[w[i]]].midCount = 0) then
      begin
        res := i - 1;
        exit;
      end;
      if i = len then
      begin
        res := i;
        exit;
      end;
      node := T[node].Next[w[i]];
      Inc(i);
    end;
  end;
(*------------------------------*)
begin
  Assign(Input, FI_NAME); Reset(Input);
  Assign(Output, FO_NAME); Rewrite(Output);
  while not SeekEOF() do
  begin
    ReadQuery();
    case k of
      0: Add();
      1: Del();
      2: begin
           res := 0;
           Count();
           WriteLn(res);
         end;
      3: begin
           res := 0;
           Count2();
           WriteLn(res);
         end;
    end;
  end;
end.