标签:
2 AAA AAG AAAG 2 A TG TGAATG 4 A G C T AGT 0
Case 1: 1 Case 2: 4 Case 3: -1
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int INF = 0x3f3f3f3f; 4 const int maxn = 1010; 5 char str[maxn]; 6 int dp[maxn][maxn],id[130],n,cs = 1; 7 8 struct Trie { 9 int ch[maxn][4],fail[maxn],tot; 10 bool flag[maxn]; 11 int newnode() { 12 memset(ch[tot],0,sizeof ch[tot]); 13 fail[tot] = flag[tot] = 0; 14 return tot++; 15 } 16 void init() { 17 tot = 0; 18 newnode(); 19 } 20 void insert(char *str,int root = 0){ 21 for(int i = 0; str[i]; ++i){ 22 if(!ch[root][id[str[i]]]) ch[root][id[str[i]]] = newnode(); 23 root = ch[root][id[str[i]]]; 24 } 25 flag[root] = true; 26 } 27 void build(int root = 0) { 28 queue<int>q; 29 for(int i = 0; i < 4; ++i) { 30 if(ch[root][i]) { 31 fail[ch[root][i]] = root; 32 q.push(ch[root][i]); 33 } 34 } 35 while(!q.empty()) { 36 root = q.front(); 37 q.pop(); 38 for(int i = 0; i < 4; ++i) { 39 int &nx = ch[root][i]; 40 if(nx) { 41 fail[nx] = ch[fail[root]][i]; 42 flag[nx] = flag[nx]||flag[fail[nx]]; 43 q.push(nx); 44 } else nx = ch[fail[root]][i]; 45 } 46 } 47 } 48 void solve(char *str) { 49 memset(dp,0x3f,sizeof dp); 50 int len = strlen(str); 51 dp[0][0] = 0; 52 for(int i = 0; i < len; ++i) 53 for(int j = 0; j < tot; ++j) { 54 if(dp[i][j] >= INF) continue; 55 for(int k = 0; k < 4; ++k) { 56 int nx = ch[j][k]; 57 if(flag[nx]) continue; 58 dp[i+1][nx] = min(dp[i+1][nx],dp[i][j] + (id[str[i]] != k)); 59 } 60 } 61 int ret = INF; 62 for(int i = 0; i < tot; ++i) 63 ret = min(ret,dp[len][i]); 64 printf("Case %d: %d\n",cs++,ret == INF?-1:ret); 65 } 66 } ac; 67 int main() { 68 for(int i = 0; i < 4; ++i) id["ATCG"[i]] = i; 69 while(scanf("%d",&n),n) { 70 ac.init(); 71 for(int i = 0; i < n; ++i) { 72 scanf("%s",str); 73 ac.insert(str); 74 } 75 ac.build(); 76 scanf("%s",str); 77 ac.solve(str); 78 } 79 return 0; 80 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4934694.html