POJ_3267_The Cow Lexicon_动态规划

准备给新生上课的ppt好花时间。


给一个长字符串和一个字典,问字符串中最少删除多少个字符,剩下的串可以由字典中的单词不重叠拼成。



Input

Line 1: Two space-separated integers, respectively: W and L
Line 2: L characters (followed by a newline, of course): the received message
Lines 3.. W+2: The cows' dictionary, one word per line

Output

Line 1: a single integer that is the smallest number of characters that need to be removed to make the message a sequence of dictionary words.


这个题不难但是我用了好几种奇怪的姿势最后看题解才做出来,一维DP,dp[i]表示从i到长串末尾最少删多少个字符满足条件,递推是这样的:

dp[i]=min( dp[i+1], dp[tem]+tem-i-tlen )

dp[i+1]是说如果舍弃i位置的字符;tem是尝试从i开始匹配一个单词,一旦匹配成功就记录tem为成功时长串的位置,tlen是匹配的字典中单词的长度。


代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
#define mxl 310
#define mxw 610
char a[mxl];
char word[mxw][30];
int w,l;
int dp[mxl];
int main(){
	while(scanf("%d%d",&w,&l)!=EOF){
		scanf("%s",a);
		for(int i=0;i<w;++i)
			scanf("%s",word[i]);
		dp[l]=0;
		for(int i=l-1;i>=0;--i){
			dp[i]=dp[i+1]+1;
			int cur1,cur2,teml;
			for(int j=0;j<w;++j)	if(word[j][0]==a[i]){
				cur1=i,cur2=0,teml=strlen(word[j]);
				while(cur2!=teml&&cur1!=l){
					if(a[cur1]==word[j][cur2])
						++cur2;
					++cur1;
				}
				if(cur2==teml)	dp[i]=min(dp[i],dp[cur1]+cur1-teml-i);
			}
		}
		printf("%d\n",dp[0]);
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值