洛谷 P1019 单词接龙

P1019 单词接龙

var a:array[1..21] of string;  b:array[1..21] of integer;
i,n,x,max:longint;   ch:char;

function min(a,b:longint):longint;
begin
  if a>b then exit(b) else exit(a);
end;

function f(a,b:string):string;
var l1,l2,i,k:longint;  s1,s2:string;
begin
  l1:=length(a);
  l2:=length(b);
  f:='';
  for i:=1 to min(l1,l2) do
  begin
    s1:=copy(a,l1-i+1,i);
    s2:=copy(b,1,i);
    if s1=s2
      then exit(copy(a,1,l1-i)+b);
  end;
end;


procedure dfs(s,s2:string);
var s1:string;i,ans1:longint;
begin
  for i:=1 to n do
  begin
    if ((pos(a[i],s2)>0) or (pos(s2,a[i])>0)) and (s2<>a[i])
      then continue;
    if (b[i]<2)
      then
      begin
        s1:=f(s,a[i]);
        if s1<>''
          then
          begin
            inc(b[i]);
            ans1:=length(s1);
            if ans1>max
              then max:=ans1;
            dfs(s1,a[i]);
            dec(b[i]);
          end;
      end;
  end;
end;
begin
  readln(n);
  for i:=1 to n do
    readln(a[i]);
  readln(ch);
  //writeln(f('aba','aa'));
  for i:=1 to n do
    if a[i][1]=ch
      then
      begin
        //max:=length(a[i]);
        inc(b[i]);
        dfs(a[i],a[i]);
        dec(b[i]);
      end;
  writeln(max);
end.
原文地址:https://www.cnblogs.com/hehe54321/p/8470462.html