hdu 1004 Let the Balloon Rise 字典树

题目:给出n个单词n<=1000,求哪个单词出现的次数最多。

分析:把每个单词插入到字典树里,记录单词出现的次数,再查找字典树,哪个单词出现的数量最多1即为输出结果。

程序:

var
  a1,n,i,ans:longint;
  str,u:string;
  s:array[1..15000] of char;
  son:array[1..15000,1..26] of longint;
  a:array[1..15000,1..2] of longint;

procedure insert(x:longint;str:string);
var
  i:longint;
begin
  if str='' then
  begin
    inc(a[x,2]);
    exit;
  end;
  for i:=1 to a[x,1] do
    if s[son[x,i]]=str[1] then
    begin
      delete(str,1,1);
      insert(son[x,i],str);
      exit;
    end;
  inc(a1);
  inc(a[x,1]);
  s[a1]:=str[1];
  a[a1,1]:=0;
  a[a1,2]:=0;
  son[x,a[x,1]]:=a1;
  delete(str,1,1);
  insert(a1,str);
end;

procedure count(x:longint;str:string);
var
  i:longint;
begin
  if a[x,2]>ans then
  begin
    ans:=a[x,2];
    u:=str;
  end;
  for i:=1 to a[x,1] do
    count(son[x,i],str+s[son[x,i]]);
end;

begin
  readln(n);
  while n>0 do
  begin
    a1:=1;
    a[1,1]:=0;
    for i:=1 to n do
    begin
      readln(str);
      insert(1,str);
    end;
    ans:=0;
    count(1,'');
    writeln(u);
    readln(n); 
  end;
end.


你可能感兴趣的:(hdu 1004 Let the Balloon Rise 字典树)