【思路要点】
- 显然有矩阵乘法优化序列自动机 d p dp dp 的做法。
- 考虑 A l A l + 1 … A r = A l − 1 − 1 … A 2 − 1 A 1 − 1 A 1 A 2 … A r A_lA_{l+1}\dots A_r=A_{l-1}^{-1}\dots A_2^{-1}A_1^{-1}A_1A_{2}\dots A_r AlAl+1…Ar=Al−1−1…A2−1A1−1A1A2…Ar ,因此只需考虑计算矩阵的前缀右乘和以及逆矩阵的前缀左乘和即可。
- 注意到矩阵具有一定特殊性,右乘一个矩阵或左乘一个矩阵的逆均对应了一种初等变换,直接维护初等变换的结果即可。
- 询问时我们只需要知道矩阵中的一个元素,暴力计算就行。
- 时间复杂度 O ( N σ + M σ ) O(N\sigma+M\sigma) O(Nσ+Mσ) 。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 5e5 + 5; const int MAXC = 256; const int MAXS = 11; 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(""); } int n, m, tot, a[MAXN]; char s[MAXN], num[MAXC]; long long A, B, C; int mat[MAXN][MAXS], matex[MAXS][MAXS]; int inv[MAXN][MAXS], invex[MAXS][MAXS]; void init() { mat[0][0] = inv[0][0] = 1; for (int i = 1; i <= tot; i++) { matex[i][i] = 1; invex[i][i] = 1; } for (int i = 1; i <= n; i++) { for (int j = 0; j <= tot; j++) { mat[i][j] = 2 * mat[i - 1][j]; if (mat[i][j] >= P) mat[i][j] -= P; mat[i][j] += matex[a[i]][j]; if (mat[i][j] >= P) mat[i][j] -= P; matex[a[i]][j] = P - mat[i - 1][j]; if (matex[a[i]][j] >= P) matex[a[i]][j] -= P; } } for (int i = 1; i <= n; i++) { for (int j = 0; j <= tot; j++) { inv[i][j] = invex[a[i]][j]; invex[a[i]][j] = 2 * invex[a[i]][j] - inv[i - 1][j]; if (invex[a[i]][j] < 0) invex[a[i]][j] += P; if (invex[a[i]][j] >= P) invex[a[i]][j] -= P; } } } int solve(int l, int r) { int ans = 0; for (int i = 0; i <= tot; i++) ans = (ans + 1ll * inv[l - 1][i] * mat[r][i]) % P; return (ans - 1 + P) % P; } int main() { scanf("%s", s + 1); n = strlen(s + 1), read(m); for (int i = 1; i <= n; i++) { if (num[s[i] - 0] == 0) num[s[i] - 0] = ++tot; a[i] = num[s[i] - 0]; } init(); for (int i = 1; i <= m; i++) { int l, r; read(l), read(r); long long ans = solve(l, r); writeln(ans); } return 0; }