前言
这题自己先是独立写了将近一下午,然后发现假了,然后看题解,原来是这么做的!学到了。
Problem
求不包含给定一个子串的字符串个数,字符均为 ~。
。
Solution
我们将考虑逐渐增加长度。
发现当前这个串是否出现给定字符串,只和最后那几个不超过 的字符有关,所以考虑从这里入手,计算长度为 的,匹配了 的长度的字符串有多少种。
具体地:
令 表示长度为 ,最后匹配了 的长度,且前面均没有匹配成功的字符串种数。
而我们可以预处理:当长度增加 ,从匹配长度为 到匹配长度为 ,的方案总数,这里时间是 。
此时就可以开一个 的矩阵,然后矩阵乘法做了。
注意上述匹配长度均为最大长度。
时间复杂度:。
Code
#include <bits/stdc++.h>
#define int long long
#define dd double
using namespace std;
template <typename T> inline void D(T &x)
{
x = 0; bool f = 0; char ch = getchar();
while('0' > ch || ch > '9') { if(ch == '-') f = !f; ch = getchar(); }
while('0' <= ch && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }
x = f ? -x : x; return;
}
template <typename T> inline void P(T x)
{
if(x < 0) putchar('-'), x = -x;
if(x > 9) P(x / 10);
putchar(x % 10 + '0'); return;
}
const int N = 25;
int n, m, mod;
char s[N], t[N];
int nxt[N], g[N][N];
struct mat
{
int jz[N][N];
mat()
{
memset(jz, 0, sizeof(jz));
};
};
mat operator * (const mat &x, const mat &y)
{
mat res;
for (int i = 1; i <= m; i ++)
{
for (int j = 1; j <= m; j ++)
{
for (int k = 1; k <= m; k ++)
{
res.jz[i][j] += x.jz[i][k] * y.jz[k][j];
res.jz[i][j] %= mod;
}
}
}
return res;
}
mat qpow_mat(mat x, int y)
{
mat res;
for (int i = 1; i <= m; i ++) res.jz[i][i] = 1;
for (; y; x = x * x, y >>= 1) if (y & 1) res = res * x;
return res;
}
int qpow(int x, int y)
{
int res = 1;
for (; y; (x *= x) %= mod, y >>= 1) if (y & 1) (res *= x) %= mod;
return res;
}
void solve()
{
cin >> n >> m >> mod;
cin >> s + 1;
for (int i = 2, p = 0; i <= m; i ++)
{
while (p && s[p + 1] != s[i]) p = nxt[p];
p = nxt[i] = p + (s[p + 1] == s[i]);
}
if (n < m) { cout << qpow(10, n) << '\n'; return; }
if (n == m) { cout << qpow(10, n) - 1 << '\n'; return; }
mat base, zy;
for (int i = 0; i < m; i ++)
{
t[i] = s[i];
for (int k = 0; k <= 9; k ++)
{
t[i + 1] = k + '0';
int res = 0;
for (int j = i + 1; j >= 1; j --)
{
int flag = 1;
int now = 1;
for (int p = i + 1 - j + 1; p <= i + 1; p ++)
{
if (t[p] != s[now]) { flag = 0; break; }
now ++;
}
if (flag) { res = j; break; }
}
g[i][res] ++;
}
}
base.jz[1][1] = 1;
for (int i = 1; i <= m; i ++)
{
for (int j = 1; j <= m; j ++)
{
zy.jz[i][j] = g[i - 1][j - 1];
}
}
mat res = base * qpow_mat(zy, n);
int ans = 0;
for (int i = 1; i <= m; i ++) ans += res.jz[1][i], ans %= mod;
cout << ans << '\n';
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
//freopen(".in", "r", stdin); freopen(".out", "w", stdout);
int T; T = 1;
while (T --) solve();
return 0;
}