ACM: dp动态规划题(难) poj 3267  …

来源:互联网 发布:深圳阿里云大厦 编辑:程序博客网 时间:2024/06/06 01:55

                                                        The Cow Lexicon

Description

Few know that the cows have their owndictionary with W (1 ≤ W ≤ 600) words, eachcontaining no more 25 of the characters 'a'..'z'. Theircowmunication 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 turnsout, the intended message was "browncow" and the two letter "d"swere noise from other parts of the barnyard.

The cows want you to help them decipher areceived message (also containing only characters in the range'a'..'z') of length L (2 ≤ L ≤ 300) charactersthat is a bit garbled. In particular, they know that the messagehas some extra letters, and they want you to determine the smallestnumber of letters that must be removed to make the message asequence of words from the dictionary.

Input

Line 1: Two space-separated integers,respectively: W and L
Line 2: L characters (followed by anewline, 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 smallestnumber of characters that need to be removed to make the message asequence of dictionary words.

Sample Input

6 10

browndcodw

cow

milk

white

black

brown

farmer

Sample Output

2

题意: 帮助牛牛们接受message, 但是message有些无用的信息(字母).现在在字典中找出删除message

        最少的字母数就可以拼出message字符串.

解题思路:

               1. 在训练册上是动态规划题. 至少有个方向.

               2. 设 dp[i] 表示:  i ~ n中至少要删除的字母个数.

               学习到 状态方程是: dp[i] = min(dp[i]+mins, dp[i+1]+1);

代码:

#include<cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 603

int W;
int L;
int dp[MAX];
char str[MAX][28];
char msg[305];

inline int min(int a,int b)
{
    return a> b ? b : a;
}

int main()
{
//   freopen("input.txt","r",stdin);
   while(scanf("%d%d",&W,&L) != EOF)
    {
      scanf("%s",msg);
      for(int i = 0; i < W; ++i)
         scanf("%s",str[i]);
         
      memset(dp,0,sizeof(dp));
      
      for(int i = L-1; i >= 0;--i)
      {
         int mins =1<<20;
         int minx;
         int a;
         for(int j = 0; j < W; ++j)
         {
            minx = 0;
            a = i;
            int len = strlen(str[j]);
            int flag = 1;
            for(int k = 0; k < len; ++k)
                    
               if(a == L)
               {
                  flag = 0;
                  break;
               }
               if(str[j][k] != msg[a])
                 
                  minx++;
                  k--;
               }
               a++;
            }
            if(flag == 1)
               mins = min(mins,minx+dp[a]);
         }
         dp[i] = min(mins,dp[i+1]+1);
      }
      printf("%d\n",dp[0]);
    }
    return0;
}

0 0
原创粉丝点击