The Cow Lexicon POJ - 3267

题目链接:https://vjudge.net/problem/POJ-3267
题目:
Few know that the cows have their own dictionary with W (1 ≤ W ≤ 600) words, each containing no more 25 of the characters ‘a’..’z’. Their cowmunication system, based on mooing, is not very accurate; sometimes they hear words that do not make any sense. For instance, Bessie once received a message that said “browndcodw”. As it turns out, the intended message was “browncow” and the two letter “d”s were noise from other parts of the barnyard.

The cows want you to help them decipher a received message (also containing only characters in the range ‘a’..’z’) of length L (2 ≤ L ≤ 300) characters that is a bit garbled. In particular, they know that the message has some extra letters, and they want you to determine the smallest number of letters that must be removed to make the message a sequence of words from the dictionary.

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.
Sample Input
6 10
browndcodw
cow
milk
white
black
brown
farmer
Sample Output
2
题意:大致就是说给你W个单词和一个长度为M的字符串,通过删除字符串里面的某些字符使字符串变成一个有意义的字符串也就是删除后字符串全由单词构成,问你最少需要删除的字符个数;
思路:最开始想的是找到字符串里面分成任意多个部分,每一个部分可以通过删除一些字母变成单词,记录需要删除的字母个数,在记录左右端点,最后在将区间组合起来,得到删除个数,但是实际上这样的时间复杂度太高了,因为你需要遍历字符串的每个字符,如果找到一个字符后跳出,得到的就不一定是最优解,然后在从单词里面查询,最后组合区间,前面时间复杂度大概就是1e8,在加一部分。
然后就换了一种思路——动态规划,用一个一维的dp数组,dp[i]就代表以i为长度的字符串需要删除最少的字符个数,使字符串满足题意,对于第i个字符,它可以有两种转态推过来,第一种就是可以构成单词的一部分,但是由于dp的定义,这个字母只有在构成单词末尾元素时才能对当前转态有影响,因为当它在单词的其他地方,在后面没有字符与它组合时都是需要被删除的,那它这个时候的值就为dp[i-len],len为单词长度,另一种就是不能构成单词的最后一位,则此时的转态就是dp[i-1]+1,在从所有的转态里面取最小值;最后dp[w]就是从1到W变成满足题意所需删除的单词数了;
AC代码:
using namespace std;
char map[605][26];
int num[605];
char x[305];
int dp[305];
int main( )
{
int n,m;
scanf(“%d %d”,&n,&m);
for(int a=1;a<=m;a++)
{
cin>>x[a];
}
for(int a=1;a<=n;a++)
{
scanf(“%s”,map[a]);
num[a]=strlen(map[a]);
}
dp[0]=0;
for(int a=1;a<=m;a++)
{
dp[a]=dp[a-1]+1;
for(int b=1;b<=n;b++)
{
bool z1=false;
int z=0;
if(x[a]==map[b][num[b]-1])
{
int d=a-1;
for(int c=num[b]-2;c>=0;d–)
{
if(d<=0)
{
z1=true;
break;
}
else if(map[b][c]!=x[d])
z++;
else
c–;
}
if(!z1)
dp[a]=min(dp[a],dp[a-num[b]-z]+z);
}
}
}
printf(“%d\n”,dp[m]);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值