The Cow Lexicon
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7900 | Accepted: 3707 |
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 2: L characters (followed by a newline, of course): the received message
Lines 3.. W+2: The cows' dictionary, one word per line
Output
Sample Input
6 10 browndcodw cow milk white black brown farmer
Sample Output
2
Source
题意:
给一个长为L的字符串和W个单词,问所给字符串至少需要删除多少个字符才能变成仅有所给单词组成的字符串,单词可以重复使用。
思路:
DP
dp[i] 表示把前i个字符变成合格字符串需要的最少步数
策略是用每一个单词来匹配下一个
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#endif
#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define REP(i, n) for(int (i)=0; (i)<n; (i)++)
#define REP1(i, n) for(int (i)=1; (i)<=(n); (i)++)
#define FOR(i, s, t) for(int (i)=(s); (i)<=(t); (i)++)
const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));
const int maxn = 300 + 20;
char s[maxn];
char dic[640][maxn];
int dp[maxn];
int main() {
int w, L;
while(scanf("%d%d", &w, &L) != EOF) {
scanf("%s", s+1);
for(int i=0; i<w; i++) {
scanf("%s", dic[i]);
}
for(int i=0; i<=L; i++) dp[i] = L;
dp[0] = 0;
for(int i=0; i<=L; i++) {
if(i) dp[i] = min(dp[i], dp[i-1]+1);
for(int j=0; j<w; j++) {
int len = strlen(dic[j]);
int cost = 0;
int p = i + 1;
int k = 0;
while(k < len) {
while(p <= L && s[p] != dic[j][k]) p++, cost++;
if(p == L+1) break;
k++;
p++;
}
p--;
if(k == len && p <= L) {
dp[p] = min(dp[p], dp[i] + cost);
}
}
}
printf("%d\n", dp[L]);
}
return 0;
}