Description
Input
Output
Sample Input
2 AAA AAG AAAG 2 A TG TGAATG 4 A G C T AGT 0
Sample Output
Case 1: 1 Case 2: 4 Case 3: -1
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int inf = 0x3f3f3f3f;
struct Trie {
int next[1010][4], fail[1010];
int end[1010];
int root, L;
int newNode() {
for (int i = 0; i < 4; i++)
next[L][i] = -1;
end[L++] = false;
return L-1;
}
void init() {
L = 0;
root = newNode();
}
int getInt(char ch) {
if (ch == ‘A‘) return 0;
else if (ch == ‘C‘) return 1;
else if (ch == ‘G‘) return 2;
else if (ch == ‘T‘) return 3;
}
void insert(char buf[]) {
int len = strlen(buf);
int now = root;
for (int i = 0; i < len; i++) {
if (next[now][getInt(buf[i])] == -1)
next[now][getInt(buf[i])] = newNode();
now = next[now][getInt(buf[i])];
}
end[now] = 1;
}
void build() {
queue<int> Q;
fail[root] = root;
for (int i = 0; i < 4; i++) {
if (next[root][i] == -1)
next[root][i] = root;
else {
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
}
while (!Q.empty()) {
int now = Q.front();
Q.pop();
if (end[fail[now]]) end[now] = 1; //notice
for (int i = 0; i < 4; i++)
if (next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else {
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
int dp[1010][1010];
int solve(char buf[]) {
int len = strlen(buf);
for (int i = 0; i <= len; i++)
for (int j = 0; j < L; j++)
dp[i][j] = inf;
dp[0][root] = 0;
for (int i = 0; i < len; i++)
for (int j = 0; j < L; j++)
if (dp[i][j] != inf) {
for (int k = 0; k < 4; k++) {
int news = next[j][k];
if (end[news]) continue;
int tmp;
if (k == getInt(buf[i]))
tmp = dp[i][j];
else tmp = dp[i][j] + 1;
dp[i+1][news] = min(dp[i+1][news], tmp);
}
}
int ans = inf;
for (int j = 0; j < L; j++)
ans = min(ans, dp[len][j]);
if (ans == inf)
ans = -1;
return ans;
}
} ac;
char buf[1010];
int main() {
int n, cas = 1;
while (scanf("%d", &n) != EOF && n) {
ac.init();
while (n--) {
scanf("%s", buf);
ac.insert(buf);
}
ac.build();
scanf("%s", buf);
printf("Case %d: %d\n", cas++, ac.solve(buf));
}
return 0;
}
原文:http://blog.csdn.net/u011345136/article/details/39530583