Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 9471 | Accepted: 4530 |
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 LLine 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
题目大意:
给定一个长度为m的母字符串,再给定n个长度不超过25的单词组成词典。问母字符串最少删除几个字符可以全部用字典里中的某个或者某些单词表示。比如样例去掉最后的两个‘d’之后是brown + cow组成的,所以输出为2.
解题思路:
读取母字符串的时候把str[0]留下以便于对应dp数组。dp[i]表示从1->i中最少要删除的字符数量
样例: 0 1 2 3 4 5 6 7 8 9 10
str[] b r o w n d c o d w
dp[] 0 1 2 3 4 0 1 2 3 4 2
根据母字符串把dp数组更新完毕之后如上所示。更新的方式是倒序更新,即遍历str[]母字符串数组,即1->m遍历,每到一个字符处便从后至前查看词典中是否存在已经可以匹配的单词,即找到字串在母串中的l,r,根据str[i]便可以更新dp[i]了,len[k]是匹配到的单词长度。
状态转移方程:
1、当匹配到单词时 dp[i] = min(dp[i],dp[l] + r - l - len[k])
2、当匹配不到单词是 dp[i] = dp[i-1] + 1
关于状态方程的解释在代码中。
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const LL Max = 1005;
const double esp = 1e-6;
//const double PI = acos(-1);
const int INF = 0x3f3f3f3f;
using namespace std;
char str[305];
char arr[605][35];
int dp[305],len[605];
int n,m;
int main(){
while(~scanf("%d %d",&n,&m)){
scanf("%s",str+1);
for(int i=0;i<n;i++){
scanf("%s",arr[i]);
len[i] = strlen(arr[i]);
}
memset(dp,INF,sizeof(dp));
dp[0] = 0;
for(int i=1;i<=m;i++){
bool f = 1;
for(int k=0,j;k<n;k++){
int l = i,r = i;
for(j=len[k]-1;j>=0 && l>=1;){
if(arr[k][j] == str[l]){
j--;
}
l--;
}
if(j == -1){
f = 0;
if(dp[i] > dp[l] + i - l - len[k])
dp[i] = dp[l] + i - l - len[k];
//从r一直匹配到l才匹配完毕词典中的一个单词,这时候应当删除的字符为r-l+1-len
//而dp[i]代表的含义是从1->r中最少要删除的字符数量
//此时r->l中要删除的字符数量已经得到了,从1->r的数量存在dp[r]中
//所以要加上dp[l],代码中的l == r,无需关心。
}
}
if(f){
dp[i] = dp[i-1] + 1;
}
}
printf("%d\n",dp[m]);
}
return 0;
}