poj2001 Shortest Prefixes (trie)

读入建立一棵字母树,并且每到一个节点就增加这个节点的覆盖数。

然后再重新扫一遍,一旦碰到某个覆盖数为1就是这个单词的最短前缀了。

不知为何下面的程序一直有bug……不知是读入的问题?

type node=record
     w:longint;
     go:array['a'..'z'] of longint;
     end;
var i,n,tot:longint;
    s:string;
    a,ans:array[0..1100] of string;
    t:array[0..1000000] of node;
procedure getintree(s:string);
 var i,now:longint;
 begin
 now:=1;
 for i:=1 to length(s) do
  begin
   inc(t[now].w);
   if t[now].go[s[i]]<>0 then now:=t[now].go[s[i]]
   else
    begin
     inc(tot);
     fillchar(t[tot].go,sizeof(t[tot].go),0);
     t[now].go[s[i]]:=tot;
     now:=tot;
    end;
  end;
 end;
procedure check(s:string;x:longint);
 var i,now:longint;
     flag:boolean;
     st:string;
 begin
 now:=1;i:=0;
 flag:=false;
 st:='';
 repeat
 inc(i);st:=st+s[i];
 now:=t[now].go[s[i]];
 if t[now].w=1 then flag:=true;
 until (flag) or (i=length(s));
 ans[x]:=st;
 end;
begin
 while true do
  begin
   readln(s);if s='' then break;
   inc(n);a[n]:=s;
   getintree(s);
  end;
 for i:=1 to n do check(a[i],i);
 for i:=1 to n do writeln(a[i],' ',ans[i]);
end.                 
原文地址:https://www.cnblogs.com/zyfzyf/p/3771733.html