The Cow Lexicon
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
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.
Line 2: L characters (followed by a newline, of course): the received message
Lines 3..W+2: The cows' dictionary, one word per line
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; }