poj3267 2010.7.29
poj3267 2010.7.29
The Cow Lexicon
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 3619 Accepted: 1594
Description
Few know that the cows have their owndictionary 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; sometimesthey hear words that do not make any sense. For instance, Bessie once receiveda message that said "browndcodw". As it turns out, the intendedmessage was "browncow" and the two letter "d"s were noisefrom other parts of the barnyard.
The cows want you to help them decipher areceived message (also containing only characters in the range 'a'..'z') oflength L (2 ≤ L ≤ 300) characters that is a bit garbled. In particular, they knowthat the message has some extra letters, and they want you to determine thesmallest number of letters that must be removed to make the message a sequenceof 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, oneword per line
Output
Line 1: a single integer that is thesmallest number 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
Source
USACO 2007 February Silver
题意就是给出一个主串,和一本字典,问最少在主串删除多少字母,可以使其匹配到字典的单词序列。
因为是匹配单词序列,而不是一个单词,所以就难一点点。上一年中大校内赛有道题题意和这个类似,之前我也谈过:给出主串,和若干个单词,问是否为主串的子序列。
这道DP维护一个f[i],表示主串第i个字母匹配时要删除的最少字母数。一开始初始化为f[0]=1,f[i]=f[i-1]+1。
然后对字典进行枚举,如果单词长度短于i+1,而且最后一位和主串的第i位相等,说明该单词存在与主串匹配的可能性。然后往前回溯,如果匹配了,就计算要删的字母数。更新f[i]的值即可。
#include <cstdio>
#include <cstring>
using namespace std;
char a[301];
char b[601][26];
int len[601],lena,n,tmp;
int f[301];
int min(int a,int b)
{
if (a<b) return a;else return b;
}
void work()
{
memset(f,0,sizeof(f));
f[0]=1;
int pos1,pos2;
for(int i=0;i<lena;i++)
{
if (i>0)
f[i]=f[i-1]+1;
for(int j=0;j<n;j++)
{
if (len[j]<=i+1 && b[j][len[j]-1]==a[i])
{
pos1=i,pos2=len[j]-1;
while (pos1>=0&&pos2>=0)
{
if(a[pos1]==b[j][pos2])
pos2--;
pos1--;
}
if(pos2<0)
{
if(pos1<0)
tmp=i+1-len[j];
else
tmp=i-pos1-len[j]+f[pos1];
f[i]=min(f[i],tmp);
}
}
}
}
printf("%d\n",f[lena-1]);
}
int main()
{
scanf("%d %d",&n,&lena);
scanf("%s",a);
memset(f,0,sizeof(f));
for(int i=0;i<n;i++)
{
scanf("%s",b[i]);
len[i]=strlen(b[i]);
}
work();
}
本文解析了POJ3267问题——The Cow Lexicon,介绍了一个字符串匹配问题,通过动态规划方法求解从给定字符串中删除最少字符数以形成字典中的单词序列。

684

被折叠的 条评论
为什么被折叠?



