The Cow Lexicon

                                      The Cow Lexicon

                                                             Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Problem 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
 
题意:给定一个字符串和几个单词,求出在字符串中需最少去掉几个字符可以让整个字符串能和若干个字符匹配。
思路:从后往前检索,运用dp思想。
状态方程:
      dp[i]=dp[i+1]+1         //不匹配的情况删除的字符数(最坏情况)

       dp[i]=min(dp[i],dp[pm]+(pm-i)-len);    ///更新(优化)dp[i]

具体的含义看代码,一看既明。

源代码:

#include<iostream>
#include<string>
using namespace std;
int min(int a,int b)
{
    return a<b ? a:b;
}
int main()
{
int i,j;
int w,l; while(cin>>w>>l) { int *dp=new int[l+1]; char *meg=new char[l]; string *dict=new string[w]; cin>>meg; for(i=0;i<w;i++) { cin>>dict[i]; } dp[l]=0; ///dp[i]表示从i到l要删除的字符数 for(i=l-1;i>=0;i--) ///从后往前依次检索 { dp[i]=dp[i+1]+1; ///不匹配的情况删除的字符数(最坏情况) for(j=0;j<w;j++) ///对所有的单词枚举检测 { int len=dict[j].length(); ///枚举的字符串长度 if( len<=l-i && dict[j][0]==meg[i]) ///该单词的长度小于等于待比较的message的长度 { int pm=i; ///meg的指针 int pd=0; ///单词的指针 while(pm<l) ///单词逐个匹配 { if(dict[j][pd]==meg[pm++]) ///每匹配一个单词指针加1 pd++; if(pd==len) ///和该单词匹配成功 { dp[i]=min(dp[i],dp[pm]+(pm-i)-len); ///更新(优化)dp[i] break; } } } } } cout<<dp[0]<<endl; ///输出结果 delete dp,meg,dict; } return 0; }

 

posted on 2013-09-17 20:15  天梦Interact  阅读(238)  评论(0编辑  收藏  举报