题目连接:https://www.luogu.com.cn/problem/P1026
思路:
将字符串分为k个区间的最大值,就是区间dp,dp(i,j)表示将1~i分为j个区间的能最多包含字符串的个数,转移方程:dp(i,t) = dp(j,t-1) + num(j+1,i);
所以要预处理出来num(i,j),表示[i,j]区间范围内包含多少个字符串。卡在细节上了,具体的看代码吧。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 205;
const unsigned int base = 131;
int n,P,K,num[N][N],dp[N][N],tot = 0,Len[N];
char s1[N],s2[N];
unsigned int h1[N],h2[N],pp[N];
int main(void)
{
pp[0] = 1; h2[0] = 0;
scanf("%d%d",&P,&K);
for(int i=1;i<=P;i++){
scanf("%s",s1);
for(int j=0;j<20;j++){
tot++;
h2[tot] = h2[tot-1]*base + s1[j];
pp[tot] = pp[tot-1]*base;
}
}
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%s",s1); Len[i] = strlen(s1);
h1[i] = 0;
for(int j=0;j<Len[i];j++)
h1[i] = h1[i]*base + s1[j];
}
//预处理i,j区间内包含的不重叠的字符串的个数
for(int i=1;i<=tot;i++)
for(int j=i;j<=tot;j++)
{
num[i][j] = 0;
for(int t1=i;t1<=j;t1++)
for(int t2=1;t2<=n;t2++)
{
if(t1-Len[t2]+1>=i && h1[t2] == h2[t1] - h2[ t1-Len[t2] ]*pp[ Len[t2] ]){
num[i][j]++;
break;//这里要断开,防止重叠,我真是个dd
}
}
}
//区间dp
for(int t=1;t<=K;t++)
for(int i=1;i<=tot;i++)
for(int j=t-1;j<=i-1;j++) //这里要注意从t-1开始
dp[i][t] = max(dp[i][t],dp[j][t-1] + num[j+1][i]);
printf("%d\n",dp[tot][K]);
return 0;
}