DNA repair

Time limit:2000ms Memory limit:32768kB

链接

http://acm.hdu.edu.cn/showproblem.php?pid=2457

题意

给出n个子串(只含有ACGT),现在给出一个长的字符串,问最少修改多少次可以使得这个长的字符串中不包含任意一个子串?

思路

题解

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstring>
using namespace std;

typedef long long ll;

const int maxn = 1005;
const int kind = 4;
const int inf = 998244353;

int dic[128];

int root, cnt;
int nxt[maxn][kind];
int fail[maxn];
int mrk[maxn];

int newnode ()
{
    ++cnt;
    for (int i = 0; i < kind; ++i) {
        nxt[cnt][i] = -1;
    }
    mrk[cnt] = 0;
    return cnt;
}

void ac_init ()
{
    cnt = -1;
    root = newnode();
}

void wd_insert (char str[])
{
    int now = root;
    int len = strlen(str);
    for (int i = 0; i < len; ++i) {
        if (nxt[now][dic[str[i]]] == -1) {
            nxt[now][dic[str[i]]] = newnode();
        }
        now = nxt[now][dic[str[i]]];
    }
    mrk[now] = 1;
}

void build ()
{
    queue<int> q;
    fail[root] = root;
    for (int i = 0; i < kind; ++i) {
        if (nxt[root][i] == -1) {
            nxt[root][i] = root;
        }
        else {
            fail[nxt[root][i]] = root;
            q.push(nxt[root][i]);
        }
    }
    while (!q.empty()) {
        int now = q.front();
        q.pop();
        mrk[now] |= mrk[fail[now]];
        for (int i = 0; i < kind; ++i) {
            if (nxt[now][i] == -1) {
                nxt[now][i] = nxt[fail[now]][i];
            }
            else {
                fail[nxt[now][i]] = nxt[fail[now]][i];
                q.push(nxt[now][i]);
            }
        }
    }
}

void init ()
{
    dic['A'] = 0;
    dic['C'] = 1;
    dic['G'] = 2;
    dic['T'] = 3;
}

int n;
char str[maxn];

int dp[maxn][maxn];

int main ()
{
    init();
    int cas = 0;
    while (scanf("%d", &n) != EOF && n) {
        ac_init();
        for (int i = 1; i <= n; ++i) {
            scanf("%s", str);
            wd_insert(str);
        }
        build();
        scanf("%s", str);
        int len = strlen(str);
        for (int i = 0; i <= len; ++i) {
            for (int j = 0; j <= cnt; ++j) {
                dp[i][j] = inf;
            }
        }
        dp[0][0] = 0;
        for (int i = 1; i <= len; ++i) {
            for (int j = 0; j <= cnt; ++j) {
                if (mrk[j]) {
                    continue;
                }
                for (int k = 0; k < kind; ++k) {
                    if (!mrk[nxt[j][k]]) {
                        dp[i][nxt[j][k]] = min(dp[i][nxt[j][k]], dp[i-1][j]+(dic[str[i-1]]!=k));
                    }
                }
            }
        }
        int res = inf;
        for (int i = 0; i <= cnt; ++i) {
            res = min(res, dp[len][i]);
        }
        cout << "Case " << ++cas << ": ";
        if (res == inf) {
            cout << -1 << '\n';
        }
        else {
            cout << res << '\n';
        }
    }
    return 0;
}

发表评论