Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7397 | Accepted: 3461 |
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 lengthL (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 2: L characters (followed by a newline, of course): the received message
Lines 3.. W+2: The cows' dictionary, one word per line
Output
Sample Input
6 10 browndcodw cow milk white black brown farmer
Sample Output
2
Source
这个题目是一道字符串dp题。
状态转移方程如下:从后往前dp
当位置i的字符可以匹配到以它为首的单词时,dp[i] = min(dp[i], dp[i+1]+1, right-i-strlen(dictword)+dp[right])
例如:dcodwe, 当dp到c时,假如可以匹配cow这个单词,则right = 5, left = 1, strlen(dictword) = 3, dp[right] = 1(只有一个e的时候,直接丢弃)
因此dp[1] = 2;
当位置i的字符没有匹配到以它为首的单词时,则dp[i] = min(dp[i], dp[i+1]+1);
提交记录:
1.AC!
代码如下:
#include
#include
#include
#include
#include
#include
#include
#define oo 1000000 using namespace std; int w, l; char str[400]; char dict[700][30]; int dp[400] = {0}; int main() { cin >> w >> l; scanf("%s", str); int i, j; for (i = 0; i < w; i++) { scanf("%s", dict[i]); } for (i = l-1; i>=0; i--) { dp[i] = oo; } assert(l==strlen(str)); for (i = l - 1; i >= 0; i--) { for (j = 0; j < w; j++) { int len = strlen(dict[j]);//存储一下len if (l-i >= len && str[i] == dict[j][0]) { int m, n; for (m = i, n = 0; m < l, n < len; m++) { if (str[m] == dict[j][n]) n++;//比较从i到末尾的字符串中,第一个匹配到dict[j]的那个串 } if (n == len) { //n加到了len,说明前面的len-1个元素都过了一遍,也就是匹配上那个词典了 dp[i] = min(dp[i], m - i - len + dp[m]); //m-i-len是匹配dict[j]所耗费的字符数量 //dp[m]是剩余的部分需要删除的字符数量 //这里当m==l的时候,也是成立的 } } } dp[i] = min(dp[i], dp[i+1] + 1);//不匹配以这个字符为首的字符串 } cout << dp[0] << endl; return 0; }