只能说这道题目的数据好强啊,以前写的自动机都是有缺陷的但是可以过题,这次被坑大发了……呜呜
f(i, j)表示长度为i的串,到j状态时需要更改的次数。
f(i, u) = min(f(i, u), f(i-1, j) + (s[i] != k))
u是状态j的子状态。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct AC_Automata {
#define N 1003
#define M 4
int ch[N][M], val[N], last[N], f[N], sz;
void clear() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
int idx(char c) {
if (c == 'A') return 0;
if (c == 'G') return 1;
if (c == 'C') return 2;
return 3;
}
void insert(char s[], int v) {
int u = 0;
for (int i=0; s[i]; i++) {
int c = idx(s[i]);
if (!ch[u][c]) {
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = 1;
}
void build() {
queue<int> q;
f[0] = 0;
for (int c=0; c<M; c++) {
int u = ch[0][c];
if (u) { f[u] = last[u] = 0; q.push(u); }
}
while (!q.empty()) {
int r = q.front(); q.pop();
for (int c=0; c<M; c++) {
int u = ch[r][c];
val[r] = val[r] || val[f[r]]; ///传递后缀串的合法性
if (!u) { ch[r][c] = ch[f[r]][c]; continue; }
q.push(u);
f[u] = ch[f[r]][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
} ac;
int f[1003][1003];
#define inf 0x3f3f3f3f
char s[1005];
void solve(int T) {
scanf(" %s", s);
int len = strlen(s);
memset(f, 0x3f, sizeof(f));
f[0][0] = 0;
int u, t;
for (int i=1; i<=len; i++) {
for (int j=0; j<ac.sz; j++) {
if (f[i-1][j] >= inf) continue;
for (int k=0; k<4; k++) {
u = ac.ch[j][k];
if (ac.val[u]) continue;
if (ac.idx(s[i-1]) == k) t = 0;
else t = 1;
f[i][u] = min(f[i][u], f[i-1][j]+t);
}
}
}
int ans = inf;
for (int i=0; i<ac.sz; i++)
if (ac.val[i] == 0) ans = min(ans, f[len][i]);
printf("Case %d: ", T);
if (ans == inf) puts("-1");
else printf("%d\n", ans);
}
int main() {
int n, T = 0;
while (scanf("%d", &n) == 1 && n) {
ac.clear();
for (int i=1; i<=n; i++) {
scanf(" %s", s); ac.insert(s, 1);
}
ac.build();
solve(++T);
}
return 0;
}