题意:
给出N个模式串和一个文本串,问最少修改文本串中多少个字母使得文本串中不包含模式串。
分析:
N个模式串构建AC自动机,然后文本串在AC自动机中走,其中单词结点不可达。
用dp[i][j]表示文本串第i个字母转移到AC自动机第j个结点最少修改字母的个数,状态转移方程为dp[i][j]=min(dp[i][j],dp[i-1][last]+add),last表示j的前趋,add为当前点是否修改。由于第i个只和第i-1个有关,所以可以使用滚动数组来优化空间。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
struct Trie
{
int next[1010][4],fail[1010];
bool 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 getch(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][getch(buf[i])] == -1)
next[now][getch(buf[i])] = newnode();
now = next[now][getch(buf[i])];
}
end[now] = true;
}
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] = true;//这里不要忘记
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[2][1010];
int solve(char buf[]){
memset(dp,INF,sizeof(dp));
dp[0][root] = 0;
int x = 1;
for(int i = 0; buf[i]; ++i,x^=1){
memset(dp[x],INF,sizeof(dp[x]));
for(int j = 0; j < L; ++j){
if(dp[x^1][j]==INF)continue;
for(int k = 0; k < 4; ++k){
int news = next[j][k];
if(end[news])continue;
int add = k==getch(buf[i])?0:1;
dp[x][news] = min(dp[x][news],dp[x^1][j]+add);
}
}
}
int ans = INF;
for(int i = 0; i < L; ++i){
ans = min(ans,dp[x^1][i]);
}
if(ans == INF)ans = -1;
return ans;
}
void debug()
{
for(int i = 0;i < L;i++)
{
printf("id = %3d,fail = %3d,end = %3d,chi = [",i,fail[i],end[i]);
for(int j = 0;j < 4;j++)
printf("%2d",next[i][j]);
printf("]\n");
}
}
};
char buf[1010];
Trie ac;
int main()
{
int n;
int iCase = 0;
while ( scanf("%d",&n) == 1 && n)
{
iCase++;
ac.init();
while(n--)
{
scanf("%s",buf);
ac.insert(buf);
}
ac.build();
//ac.debug();
scanf("%s",buf);
printf("Case %d: %d\n",iCase,ac.solve(buf));
}
return 0;
}