题意:给出n个病毒的DNA序列。给出一串DNA序列。问至少需要更改几个该序列中的字符,是该序列不包含任何一个病毒序列。
思路:AC自动机+DP
首先我们可以根据病毒的DNA序列构造出AC自动机,同时对为病毒序列打上标记。需要注意的是:如果某个节点的fial指针指向了被打上标记的节点,说明该字符串包含该病毒序列,同样要打上标记。
那么,我们最终的目标是让给定的DNA序列在AC自动机上无法匹配。等价的意思是,除了被标记的节点,AC自动机上的节点可以任意到达。
设dp[i][j]为对于前i个,位于AC自动机上的节点j,最少需要改变字符的个数。则,对于节点j的儿子k 1:如果是标记节点,不可到达。2.对应字符和给出序列的字符相同,不需要改变。3.对应字符和序列的下一个字符不同,需要改变。
所以DP方程为: dp[i+1][k] = min(dp[i+1][k], dp[i][j] + (k != s[i]))
初始化:dp[0][root] = 0; 最后的结果为dp[n][j]中的最小值。
代码如下:(kaungbin大大的)
#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[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 == getch(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;
}
};
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();
scanf("%s",buf);
printf("Case %d: %d\n",iCase,ac.solve(buf));
}
return 0;
}