POJ2001 Shortest Prefixes (Trie树)

直接用Trie树即可。

每个节点统计经过该点的单词数,遍历时当经过的单词数为1时即为合法的前缀。

type arr=record
        next:array['a'..'z'] of longint;
        w:longint;
        end;
const maxn=10008;
var T:array[0..maxn] of arr;
    s:array[0..maxn] of ansistring;
    i,j,m,n,now,num:longint;
begin
  while not eof do
    begin
      inc(n);
      readln(s[n]);
    end;
  num:=1;
  for i:=1 to n do
    begin
      now:=1;
      for j:=1 to length(s[i]) do
        begin
          if T[now].next[s[i][j]]<>0 then now:=T[now].next[s[i][j]] else
            begin
              inc(num);
              T[now].next[s[i][j]]:=num;
              now:=num;
            end;
          inc(T[now].w);
        end;
    end;
  for i:=1 to n do
    begin
      write(s[i],' ');
      now:=1;
      for j:=1 to length(s[i]) do
        begin
          now:=T[now].next[s[i][j]];
          write(s[i][j]);
          if T[now].w=1 then break;        
        end;    
      writeln;
    end;

end.
原文地址:https://www.cnblogs.com/rpSebastian/p/4165867.html