poj 3267 The Cow Lexicon(枚举+DP) @

来源:互联网 发布:淘宝健身教练靠谱吗 编辑:程序博客网 时间:2024/06/06 12:31

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 10browndcodwcowmilkwhiteblackbrownfarmer
Sample Output
2


给一个字符串,和一个字符串字典,问在原字符串中最少删去几个字符后,原字符串中的每个单词都可以在字典中找到;


#include <iostream>#include <cstdio>#include <cstring>#include <climits>#include <vector>#include <queue>#include <algorithm>using namespace std;const int N = 1000;int dp[N];char str[N][N], s[N];int main(){    int n, m;    while(scanf("%d %d", &n, &m)!=EOF)    {        scanf("%s",s);        for(int i=0;i<n;i++) scanf("%s",str[i]);        memset(dp,0,sizeof(dp));        for(int i=m-1;i>=0;i--)        {            dp[i]=dp[i+1]+1;//最坏的情况              for(int j=0;j<n;j++) //遍历所有字典中的单词              {                int len=strlen(str[j]);                if(str[j][0]==s[i]&&m-i>=len) //如果从i出发长度够长,并且i位置的字母与其首字母相同                  {                    int ps=0, pr=i;//原单词的指针和字典中单词的指针                      while(pr<m)                    {                        if(str[j][ps]==s[pr++]) ps++;                        if(ps>=len) dp[i]=min(dp[i],dp[pr]+pr-i-len);//如果从i开始s含有这个单词,那么得删去的长度就为ps-i-len,dp[i] = dp[ps]+(ps-i-len)                      }                }            }        }        printf("%d\n",dp[0]);    }    return 0;}


0 0
原创粉丝点击