The Cow Lexicon
Description
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
题目大意:
题意就是给出一个主串,和一本字典,问最少在主串删除多少字母,可以使其匹配到字典的单词序列.
PS:是匹配单词序列,而不是一个单词
解题思路:
动态规划。网上多数是从后往前推。我从前往后推也AC了。发现更好理解一些。
具体细节看代码。
Code:
/*************************************************************************
> File Name: poj3267.cpp
> Author: Enumz
> Mail: 369372123@qq.com
> Created Time: 2014年10月17日 星期五 18时28分18秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<list>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#define MAXN 1001
using namespace std;
char dic[MAXN][MAXN];
char mes[MAXN];
int dp[MAXN];
int N,M;
int Incl(int i,int j) //判断字典j是否包含在字符串前i位内
{
int Ndic=strlen(dic[j])-;
if (dic[j][Ndic]!=mes[i]) return -;
while ()
{
if (Ndic==-||i==-) break;
if (dic[j][Ndic]==mes[i]) i--,Ndic--;
else i--;
}
if (Ndic==-) return i+; //返回字典i匹配的第一个字符的位置。
else return -;
}
int solve()
{
for (int i=; i<=M-; i++)
{
if (i!=)
dp[i]=dp[i-]+;
else
dp[i]=;
for (int j=; j<=N; j++)
{
int k=Incl(i,j); //判断字典j是否包含在字符串前i位内
if (k!=-)
{
//回溯到字符串开头处时,需要特判。注意if语句!WA了好几遍
if (k-<&&dp[i]>i+-k-strlen(dic[j]))
dp[i]=(i+-k-strlen(dic[j]));
else if (dp[i]>dp[k-]+i+-k-strlen(dic[j]))
dp[i]=dp[k-]+i+-k-strlen(dic[j]);
}
}
}
return dp[M-];
}
int main()
{
while (scanf("%d%d",&N,&M)!=EOF)
{
memset(dp,,sizeof(dp));
memset(dic,,sizeof(dic));
memset(mes,,sizeof(mes));
scanf("%s",mes);
for (int i=; i<=N; i++)
scanf("%s",dic[i]);
printf("%d\n",solve());
}
return ;
}