题目:
http://poj.org/problem?id=3267
题意:
给定w个字符串,再给定一个长度为l的字符串(设为str),问使用之前的w个字符串去匹配str,str中多余的字符最少有多少个,其中w个字符串可以重复使用。
思路:
定义dp[i]为从str[i]至str[l-1]中多余字符的最少个数,对于当前位置str[i],当w中某个字符串与str匹配时,那么dp[i] = min(dp[i], dp[a] + a-i-len),其中a是与str匹配的最后一个字符的位置。若全不匹配,说明当前字符多余,那么dp[i] = dp[i+1] + 1。可以看出是逆序循环str字符串。代码如下
总结:
dp真特么是菜到爆啊!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 610;
char s[N][30], str[N];
int dp[N];
int main()
{
int w, l;
while(~ scanf("%d%d", &w, &l))
{
scanf("%s", str);
for(int i = 0; i < w; i++) scanf("%s", s[i]);
memset(dp, 0x3f, sizeof dp);
dp[l] = 0;
for(int i = l-1; i >= 0; i--)
{
dp[i] = dp[i+1] + 1;
for(int j = 0; j < w; j++)
{
int len = strlen(s[j]);
if(i + len <= l && str[i] == s[j][0])
{
int a = i, b = 0;
while(a < l && b < len)
if(str[a] == s[j][b]) a++, b++;
else a++;
if(b == len) dp[i] = min(dp[i], dp[a] + a-i-len);
}
}
}
printf("%d\n", dp[0]);
}
return 0;
}