P3763 [TJOI2017]DNA

· · 题解

一个文本串一个模式串,求文本串中有多少个长度为模式串长度的子串修改不超过三次与模式串相等。

利用后缀自动机的有向无环图,把文本串建成自动机,用深搜方式把模式串放在上面匹配,如果能匹配成功就顺着走,若匹配不成功且当前修改次数少于三就记录一个修改次数,然后继续转移,匹配长度与模式串相等就记录该节点子树大小。

能想到后缀自动机的图形结构然后搜索本题就不难了。

#include <bits/stdc++.h>
#define N 100010
using namespace std;

char s[N], str[N];
int T, n, m, val[4], cnt[N], order[N << 1], siz[N << 1], ans;

struct SAM{
    int fa, len, nex[4];
}sam[N << 1];

int tot = 1, last = 1;
void add(int x) {
    int now = ++tot, p = last;
    sam[now].len = sam[p].len + 1;
    siz[now] = 1;
    for( ;p && !sam[p].nex[x]; p = sam[p].fa) sam[p].nex[x] = now;

    if(!p) sam[now].fa = 1;
    else {
        int q = sam[p].nex[x];
        if(sam[q].len == sam[p].len + 1) sam[now].fa = q;
        else {
            int tmp = ++tot;
            sam[tmp] = sam[q];
            sam[q].fa = sam[now].fa = tmp;
            sam[tmp].len = sam[p].len + 1;
            for( ;p && sam[p].nex[x] == q;p = sam[p].fa) sam[p].nex[x] = tmp;
        }
    }
    last = now;
}
void topo() {
    for(int i = 1;i <= tot; ++i) ++cnt[sam[i].len];
    for(int i = 1;i <= n; ++i) cnt[i] += cnt[i - 1];
    for(int i = 1;i <= tot; ++i) order[cnt[sam[i].len]--] = i;
    for(int i = tot, now; i >= 1; --i) {
        now = order[i];
        siz[sam[now].fa] += siz[now]; 
    }
}
void dfs(int now/*当前节点*/, int len/*匹配长度*/, int fix/*修改次数*/) {
    if(len == m) {
        ans += siz[now];
        return;
    }
    for(int i = 0;i < 4; ++i) {
        int to = sam[now].nex[i];
        if(!to) continue;
        if(i == val[str[len + 1] - 'A']) dfs(to, len + 1, fix);//不修改
        else if(fix < 3) dfs(to, len + 1, fix + 1);//修改
    }
    return;
}
void clear() {
    ans = 0;
    last = tot = 1;
    memset(sam, 0, sizeof(sam));
    memset(siz, 0, sizeof(siz));
    memset(cnt, 0, sizeof(cnt));
}

int main() {
    val['A' - 'A'] = 0, val['T' - 'A'] = 1, val['C' - 'A'] = 2, val['G' - 'A'] = 3;
    scanf("%d", &T);
    while(T--) {
        clear();
        scanf("%s\n%s", s + 1, str + 1);
        n = strlen(s + 1), m = strlen(str + 1);
        for(int i = 1;i <= n; ++i)  add(val[s[i] - 'A']);
        // cout << tot << endl;
        topo();
        dfs(1, 0, 0);
        printf("%d\n", ans);
    }
    return 0;
}