codevs天梯 统计单词个数

来源:互联网 发布:风月知相思蓝语凌云 编辑:程序博客网 时间:2024/06/04 17:46

给出一个长度不超过200的由小写英文字母组成的字母串(约定;该字串以每行20个字母的方式输入,且保证每行一定为20个)。要求将此字母串分成k份(1<k<=40),且每份中包含的单词个数加起来总数最大(每份中包含的单词可以部分重叠。当选用一个单词之后,其第一个字母不能再用。例如字符串this中可包含this和is,选用this之后就不能包含th)(管理员注:这里的不能再用指的是位置,不是字母本身。比如thisis可以算做包含2个is)。
单词在给出的一个不超过6个单词的字典中。
要求输出最大的个数。

分析:比较容易的划分动态规划,

      状态转移方程:f[i,j]=max(f[l,j-1]+total[l+1,i]);

同时,total也要动态规划(否则要超时==);

状态转移方程:total[i,j]=total[i,j-1]+word1(i,j)

const
  maxn=200;


var
    hash:array[0..maxn] of boolean;
    total:array[0..maxn,0..maxn] of longint;
    f:array[0..maxn,0..6] of longint;
    m,n,i,j,k,l,s,l1,p:longint;
    dic:array[1..6] of string;
    st,t:string;


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


function word1(be,en:longint):longint;
var i:longint;
begin
  word1:=0;
  for i:=1 to s do
    if (en-length(dic[i])+1>=be)and hash[en-length(dic[i])+1] and(copy(st,en-length(dic[i])+1,length(dic[i]))=dic[i]) then
    begin
      inc(word1);
      hash[en-length(dic[i])+1]:=false;
    end;
end;


function word2(j:longint):longint;
var i:longint;
begin
  for i:=1 to s do
    if (st[j]=dic[i]) and hash[j] then
    begin
      hash[j]:=false;
      exit(1);
    end;
  word2:=0;
end;


begin
  readln(m);
  for l1:=1 to m do
  begin
    fillchar(f,sizeof(f),0);
    readln(p,k);
    st:='';
    for i:=1 to p do
    begin
      readln(t);
      st:=st+t;
    end;
    n:=p*20;
    readln(s);
    for i:=1 to s do
      readln(dic[i]);
    for i:=1 to n do
    begin
      fillchar(hash,sizeof(hash),true);
      for j:=i to n do
        if i<>j then
          total[i,j]:=total[i,j-1]+word1(i,j)
        else
          total[i,j]:=word2(j);
    end;
    for i:=1 to n do
      f[i,1]:=total[1,i];
    for i:=2 to n do
      for j:=2 to k do
        if j<i then
          for l:=j to i-1 do
            f[i,j]:=max(f[l,j-1]+total[l+1,i],f[i,j]);
    writeln(f[n,k]);
  end;
end.

0 0