P1026 统计单词个数(区间dp + 哈希)

题目连接: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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值