记忆化搜索+AC自动机
我这题犯的最大的错误就是 写记忆化搜索的时候,进去之后就将dp值赋为0,这样如果后面没有可行方案的话dp值还是0。
多组测试样例的模板
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 2000;
const int N = 2000;
int ch[N][4],tot,f[N],val[N],last[N];
queue<int> que;
map<char,int> ma;
void init(){
tot = 0;
memset( ch[0],0,sizeof( ch[0] ) );
}
void Insert( char* str ){
int p = 0;int n = strlen( str );
for( int i = 0;i < n;i++ ){
int c = ma[str[i]];
if( !ch[p][c] ) {
ch[p][c] = ++tot;val[tot]= last[tot] = f[tot] = 0;
memset( ch[tot],0,sizeof( ch[tot] ) );
}
p = ch[p][c];
}
val[p] = 1;
}
void getfail(){
for( int i = 0;i < 4;i++ ){
if( ch[0][i] ) que.push( ch[0][i] );
}
while(que.size()){
int x = que.front();que.pop();
for( int c = 0;c < 4;c++ ){
if( !ch[x][c] ){
ch[x][c] = ch[ f[x] ][c];
continue;
}
f[ ch[x][c] ] = ch[ f[x] ][c];
last[ch[x][c]] = val[ f[ ch[x][c] ] ] ? f[ch[x][c]] : last[ f[ ch[x][c] ] ];
que.push(ch[x][c]);
}
}
}
char str[maxn];
const int mod = 10007;
int dp[N][maxn],ans,m,len;
int dfs( int x,int p ){
if( p == len ) return 0;
if( dp[x][p] != -1 ) return dp[x][p];
int mn = 0x3f3f3f3f;
bool flag = false;
mn = 0x3f3f3f3f;
for( int c = 0;c < 4;c++ ){
if( !val[ ch[x][c] ] && ! val[ last[ch[x][c]] ] ){
int cur = dfs( ch[x][c],p+1 );
if( cur != -1 ){
flag = true;
if( ma[str[p]] != c ) cur++;
mn = min( mn,cur );
}
}
}
dp[x][p] = 0x3f3f3f3f;
if(!flag ) return -1;
dp[x][p] = mn;
return dp[x][p];
}
int main(){
ma['A'] = 0;ma['G'] = 1;ma['C'] = 2;ma['T'] = 3;
int n;
int tt = 0;
while( 1 == scanf("%d",&n) && n ){
tt++;
init();
for( int i = 1;i <= n;i++ ){
scanf("%s",str);
Insert(str);
}
getfail();
for( int i = 0;i <= tot;i++ ){
memset( dp[i],-1,sizeof(dp[i]) );
}
scanf("%s",str);
len = strlen(str);
int ans = dfs( 0,0 );
if( ans >= 0x3f3f3f3f ) ans = -1;
printf("Case %d: %d\n",tt,ans);
}
return 0;
}