【poj 3267】The Cow Lexicon(DP)

时间:2022-08-07 03:41:31

The Cow Lexicon
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 11319   Accepted: 5415

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

动态规划,由于输入的长度为L,我们让dp[i]代表从下标i到l-1最少删除的字符个数。让字典里面的每个单词和它进行匹配;

先对dp[i]进行初始化,考虑到最糟糕的情况的话就是删除所有的字符串,则dp[i]=dp[i+1]+1;

假设从下标re处对第j个单词进行匹配,匹配过程有t个相等的字符,当t等于该单词长度的时候结束匹配,

此时dp[i]=min(dp[i],dp[re]+re-i-单词长度);从l-1循环到0,答案就是dp[0];

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAXN 1005

char mes[MAXN];//奶牛接收的消息

string dic[MAXN];//字典

int longth[MAXN];//字典中每个单词的长度

int dp[MAXN];//dp[i]代表从i到l至少要删除的字符个数

int n,l;//字典大小和消息长度
int main()
{
    cin>>n>>l;
    for(int i=0;i<l;i++) cin>>mes[i];
    for(int i=0;i<n;i++) {
        cin>>dic[i];
        longth[i]=dic[i].length();
    }
    memset(dp,0,sizeof(dp));// 初始化
    for(int i=l-1;i>=0;i--){
        dp[i]=dp[i+1]+1;//最坏的情况就是删掉字符
        for(int j=0;j<n;j++){//字典序暴力匹配
            if(dic[j][0]==mes[i]){//找到可能的匹配开始点
                int re=i;//记录下来从当前点开始
                int t=0;
                while(re<l){
                    if(dic[j][t]==mes[re++]){
                        t++;
                    }
                    if(t==longth[j]){
                        dp[i]=min(dp[i],dp[re]+re-i-longth[j]);//状态转移方程
                        break;
                    }
                }
            }
        }
    }
    cout<<dp[0]<<endl;
    return 0;
}