奥赛一本通 1485 文本生成器

1485 文本生成器

题目大意

给定若干单词,计算有多少个长度为 $m$ 的大写字母串至少包含一个给定单词。

知识要点

AC 自动机、动态规划

解题思路

考虑用字符串总数减去不包含给定单词的字符串数量,使用 $dp_{i,j}$ 表示长度为 $i$ 且能匹配自动机上 $j$ 号点的字符串数量。在 AC 自动机上标记包含给定单词的节点,沿着节点之间的边转移。

参考代码

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

const int N = 6005, M = 10007;
char s[N], flag[N];
int cnt, trie[N][26], fail[N];
int Q[N], dp[105][N];
void insert(char* s) {
    int p = 0;
    for(int i = 0; s[i]; i++) {
        int c = s[i] - 'A';
        if(!trie[p][c]) trie[p][c] = ++cnt;
        p = trie[p][c];
    }
    flag[p] = 1;
}
void build() {
    for(int l = 0, r = 1; l != r; l++) {
        int f = Q[l], y = fail[f];
        flag[f] |= flag[y];

        for(int c = 0; c < 26; c++) {
            int x = trie[f][c];
            if(x) Q[r++] = x, fail[x] = f ? trie[y][c] : 0;
            else trie[f][c] = trie[y][c];
        }
    }
}

int main() {
    int n, m, ans;
    scanf("%d %d", &n, &m);
    while(n--) scanf("%s", s), insert(s);
    build();
    ans = dp[0][0] = 1;

    for(int i = 1; i <= m; i++) {
        ans = ans * 26 % M; //计算总方案数 
        
        for(int f = 0; f <= cnt; f++) for(int c = 0; c < 26; c++) {
            int x = trie[f][c];
            if(flag[x]) continue;
            dp[i][x] = (dp[i][x] + dp[i - 1][f]) % M;
        }
    }

    for(int f = 0; f <= cnt; f++) ans = (ans - dp[m][f] + M) % M;
    printf("%d\n", ans);
    return 0;
}
posted @ 2026-11-20 21:58  萧西待水  阅读(3)  评论(0)    收藏  举报