您的位置:首页 > 其它

poj 3267 The Cow Lexicon

2016-08-05 15:40 363 查看
The Cow Lexicon

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 9814 Accepted: 4716
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

Source

USACO 2007 February Silver

这个题就是上面的“单句”(也就是第一个字符串,以后我就叫他单句了,哈哈!)

和下面的“单词”(以后我就简单叫他们单词了)进行匹配,看看最少在单句中删除多少个字符可以由下面的单词组合而成,,

上面的例题就是去掉两个d就可以了,,

一那到这个题感到我从下手,怎么做呢?

找题解吧!哈哈


然后就懂了

我大体说说思路吧,

就是用一个dp数组储存从单句的第几个往后数要去掉字符的个数,额好像不好懂的样子,

就举个例子,例题最后的dp[9] = 0,dp[8] = 1(第9个字符往后要去掉的个数),以此类推,dp[5] = 2啦,dp[0] = 2,也就是最后的答案了,,

然后我们要从最坏的情况开始就是从dp[9] = 1,dp[8] = 2,dp[7] = 3,..(意思就是这么个意思)一点一点的更新dp的值,

从后往前,当然开始匹配也是有条件的,最差也是头一个要相等吧,单句剩下的要大于等于单词数吧,

当你找到第一个匹配好的字符时,ss代表单句的匹配位置,t代表单词位置,

只有当单词的最后一个字符匹配成功时才能更新dp数组,

那怎样更新呢?

当然是你匹配的单句(开始与结束的差)减去(匹配单词的长度)『这里就表示你要删除的字符数啦』还要加上dp结束的值

代码如下

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int dp[350];
char a[350];
char ch[1020][350];
int len[1020];
int main()
{
int n,m,i,j;
int ss;
int t;
memset(dp,0,sizeof(dp));
scanf("%d %d",&n,&m);
scanf("%s",a);
for(i = 0;i < n; i++)
{
scanf("%s",ch[i]);
getchar();
len[i] = strlen(ch[i]);
}
int L = strlen(a);
for(i = L-1;i >= 0; i--)
{
dp[i] = dp[i+1]+1;     //每次从最差的境况入手
for(j = 0;j < n; j++)
{
if(ch[j][0] == a[i]&&L-i >= len[j])   //当你可以匹配时
{
ss = i;
t = 0;
while(ss < L)
{
if(ch[j][t] == a[ss])
{
t++;
}
ss++;
if(t == len[j])   //只有这样才能更新数组
{
dp[i] = min(dp[i],dp[ss]+ss-i-len[j]);       //就是上面我说的最后一句
//(ss-i)是匹配的单句长度,ss-i-len[j],是要删除的字符数,当然不要忘了加上之前的dp[ss]
}
}
}
}
}
printf("%d\n",dp[0]);//结果
}


代码菜鸟,如有错误,请多包涵!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: