CHAIN2 - Chuỗi từ

Tác giả: ll931110

Ngôn ngữ: Pascal

{$MODE DELPHI,H+}
program CHAIN2;
const
  input  = '';
  output = '';
type
  ptree = ^ttree;
  ttree = record
    val: integer;
    q: array['a'..'z'] of ptree;
  end;
var
  root: ptree;
  n,max: integer;

procedure Trie;
var
  f: text;
  i,j: integer;
  ch: char;
  s: string;
  p,t: ptree;
begin
  assign(f, input);
    reset(f);

  new(root);
  root^.val := 0;
  for ch := 'a' to 'z' do root^.q[ch] := nil;

  readln(f, n);
  for i := 1 to n do
    begin
      readln(f, s);
      p := root;

      for j := 1 to length(s) do
        begin
          t := p^.q[s[j]];
          if t = nil then
            begin
              new(t);
              t^.val := 0;
              for ch := 'a' to 'z' do t^.q[ch] := nil;
              p^.q[s[j]] := t;
            end;
          p := t;
        end;

      p^.val := 1;
    end;

  close(f);

  max := 1;
end;

procedure calc(p: ptree);
var
  ch: char;
  t: ptree;
begin
  for ch := 'a' to 'z' do
    begin
      t := p^.q[ch];
      if t <> nil then
        begin
          t^.val := t^.val + p^.val;
          if max < t^.val then max := t^.val;
          calc(t);
        end;
    end;
end;

procedure printresult;
var
  f: text;
begin
  assign(f, output);
    rewrite(f);
    writeln(f, max);
  close(f);
end;

begin
  Trie;
  calc(root);
  printresult;
end.

Download