题意:给出nn(1≤n≤50,1≤n≤50) 个病毒DNA序列,长度均不超过20。现在给出一个长度不超过1000的字符串,求至少要更换多少个字符,
才能使这个字符串不包含这些DNA序列。
析:利用前缀来做好状态转移。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e16; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1000 + 10; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } string str; vector<string> v, prx; int dp[maxn][maxn], nxt[maxn][4]; bool nt[maxn]; const char *ACGT = "ACGT"; int main(){ int kase = 0; while(scanf("%d", &n) == 1 && n){ string s; v.clear(); prx.clear(); for(int i = 0; i < n; ++i){ cin >> s; v.push_back(s); } cin >> str; for(int i = 0; i < n; ++i) for(int j = 0; j <= v[i].size(); ++j) prx.push_back(v[i].substr(0, j)); sort(prx.begin(), prx.end()); prx.erase(unique(prx.begin(), prx.end()), prx.end()); for(int i = 0; i < prx.size(); ++i){ nt[i] = false; for(int j = 0; j < n && !nt[i]; ++j) nt[i] |= v[j].size() <= prx[i].size() && prx[i].substr(prx[i].size()-v[j].size()) == v[j]; if(nt[i]) continue; for(int j = 0; j < 4; ++j){ s = prx[i] + ACGT[j]; int k; while(1){ k = lower_bound(prx.begin(), prx.end(), s) - prx.begin(); if(k < prx.size() && prx[k] == s) break; s = s.substr(1); } nxt[i][j] = k; } } memset(dp, INF, sizeof dp); dp[0][0] = 1; for(int i = 1; i < prx.size(); ++i) dp[0][i] = 0; for(int t = 0; t < str.size(); ++t){ for(int i = 0; i < prx.size(); ++i){ if(nt[i]) continue; for(int j = 0; j < 4; ++j){ int k = nxt[i][j]; dp[t+1][k] = min(dp[t+1][k], dp[t][i] + (str[t] != ACGT[j])); } } } int ans = INF; for(int i = 0; i < prx.size(); ++i) if(!nt[i]) ans = min(ans, dp[str.size()][i]); printf("Case %d: %d\n", ++kase, ans == INF ? -1 : ans); } return 0; }