【题目链接】
【思路要点】
- 对模式串建立AC自动机,在上面数位DP即可。
- 注意模式串可能包含前导零。
- 时间复杂度\(O(N*L)\)。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 2005; 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(""); } struct ACAutomaton { struct Node { int child[10]; int fail; bool dis; } a[MAXN]; int root, size; int dp[MAXN][MAXN][2][2]; void insert(char *s) { int len = strlen(s + 1), now = root; for (int i = 1; i <= len; i++) { int tmp = s[i] - '0'; if (a[now].child[tmp] == 0) a[now].child[tmp] = ++size; now = a[now].child[tmp]; } a[now].dis = true; } void build() { static int q[MAXN]; int l = 0, r = -1; for (int i = 0; i < 10; i++) if (a[root].child[i]) q[++r] = a[root].child[i]; while (l <= r) { int tmp = q[l++]; for (int i = 0; i < 10; i++) if (a[tmp].child[i]) { a[a[tmp].child[i]].fail = a[a[tmp].fail].child[i]; q[++r] = a[tmp].child[i]; } else a[tmp].child[i] = a[a[tmp].fail].child[i]; a[tmp].dis |= a[a[tmp].fail].dis; } } void update(int &x, int y) {x = (x + y) % P; }; int query(int n, char *s) { dp[0][root][0][0] = 1; for (int i = 0; i <= n - 1; i++) for (int j = 0; j <= size; j++) { if (a[j].dis) continue; int tmp = dp[i][j][0][1]; int tnp = dp[i][j][1][1]; for (int k = 0; k < 10; k++) { if (a[a[j].child[k]].dis) continue; if (k < s[i + 1] - '0') update(dp[i + 1][a[j].child[k]][1][1], tmp); if (k == s[i + 1] - '0') update(dp[i + 1][a[j].child[k]][0][1], tmp); update(dp[i + 1][a[j].child[k]][1][1], tnp); } tmp = dp[i][j][0][0]; tnp = dp[i][j][1][0]; for (int k = 1; k < 10; k++) { if (a[a[j].child[k]].dis) continue; if (k < s[i + 1] - '0') update(dp[i + 1][a[j].child[k]][1][1], tmp); if (k == s[i + 1] - '0') update(dp[i + 1][a[j].child[k]][0][1], tmp); update(dp[i + 1][a[j].child[k]][1][1], tnp); } dp[i + 1][j][1][0] = (tmp + tnp) % P; } int ans = 0; for (int i = 0; i <= size; i++) { update(ans, dp[n][i][1][1]); update(ans, dp[n][i][0][1]); } return ans; } } ACAT; char s[MAXN], t[MAXN]; int main() { scanf("%s", s + 1); int n = strlen(s + 1); int m; read(m); for (int i = 1; i <= m; i++) { scanf("%s", t + 1); ACAT.insert(t); } ACAT.build(); writeln(ACAT.query(n, s)); return 0; }