【题目链接】
【思路要点】
- 在SAM上DP,转移较为显然。
- 时间复杂度\(O(|S|*\sum|T|)\),其中\(\sum|T|\)为模式串长度总和。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 20005; const int MAXK = 105; const int P = 1e9 + 7; template <typename T> void chkmax(T &x, T y) {x = max(x, y); } template <typename T> void chkmin(T &x, T y) {x = min(x, y); } template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } void update(int &x, int y) { x += y; if (x >= P) x -= P; } struct SuffixAutomaton { struct Node { int child[26]; int father, depth, size; } a[MAXN]; vector <int> e[MAXN]; int dp[MAXK][MAXN]; int root, size, last, n; int newnode(int dep) { size++; a[size].depth = dep; return size; } void extend(int ch) { int p = last, np = newnode(a[p].depth + 1); while (a[p].child[ch] == 0) { a[p].child[ch] = np; p = a[p].father; } if (a[p].child[ch] == np) a[np].father = root; else { int q = a[p].child[ch]; if (a[p].depth + 1 == a[q].depth) a[np].father = q; else { int nq = newnode(a[p].depth + 1); memcpy(a[nq].child, a[q].child, sizeof(a[q].child)); a[nq].father = a[q].father; a[q].father = a[np].father = nq; while (a[p].child[ch] == q) { a[p].child[ch] = nq; p = a[p].father; } } } a[last = np].size++; } void dfs(int pos) { for (unsigned i = 0; i < e[pos].size(); i++) { dfs(e[pos][i]); a[pos].size += a[e[pos][i]].size; } } void init(char *s) { n = strlen(s + 1); root = size = last = 0; for (int i = 1; i <= n; i++) extend(s[i] - 'A'); for (int i = 1; i <= size; i++) e[a[i].father].push_back(i); dfs(root); } void calc(int k) { static char s[MAXN]; dp[0][root] = 1; for (int i = 1; i <= k; i++) { int cnt; read(cnt); while (cnt--) { scanf("\n%s", s + 1); int len = strlen(s + 1); for (int from = 0; from <= size; from++) { if (dp[i - 1][from] == 0) continue; int now = from; for (int j = 1; j <= len; j++) if (a[now].child[s[j] - 'A'] == 0) { now = -1; break; } else now = a[now].child[s[j] - 'A']; if (now != -1) update(dp[i][now], dp[i - 1][from]); } } } int ans = 0; for (int i = 0; i <= size; i++) update(ans, 1ll * a[i].size * dp[k][i] % P); writeln(ans); } } SAM; char s[MAXN]; int main() { int n; read(n); scanf("%s", s + 1); SAM.init(s); SAM.calc(n); return 0; }