题意:给出一个字符集和一个字符串和正整数n,问由给定字符集组成的所有长度为n的串中不以给定字符串为连续子串的有多少个?
析:n 实在是太大了,如果小的话,就可以用动态规划做了,所以只能用矩阵快速幂来做了,dp[i][j] 表示匹配完 i 到匹配 j 个有多少种方案,利用矩阵的性质,就可以快速求出长度为 n 的个数,对于匹配的转移,正好可以用KMP的失配函数来转移。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e16; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-6; const int maxn = 50 + 10; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r > 0 && r <= n && c > 0 && c <= m; } char s[maxn], t[maxn]; int f[maxn]; struct Matrix{ unsigned int a[maxn][maxn]; int n; Matrix(int nn) : n(nn){ memset(a, 0, sizeof a); } void toOne(){ for(int i = 0; i < n; ++i) a[i][i] = 1; } friend Matrix operator * (const Matrix &lhs, const Matrix &rhs){ Matrix res(lhs.n); for(int i = 0; i < lhs.n; ++i) for(int j = 0; j < rhs.n; ++j) for(int k = 0; k < lhs.n; ++k) res.a[i][j] += lhs.a[i][k] * rhs.a[k][j]; return res; } }; Matrix fast_pow(Matrix a, int n){ Matrix res(a.n); res.toOne(); while(n){ if(n&1) res = res * a; a = a * a; n >>= 1; } return res; } void getFail(char *s, int n){ f[0] = f[1] = 0; for(int i = 1; i < n; ++i){ int j = f[i]; while(j && s[j] != s[i]) j = f[j]; f[i+1] = s[i] == s[j] ? j+1 : 0; } } int main(){ int T; cin >> T; for(int kase = 1; kase <= T; ++kase){ scanf("%d", &n); scanf("%s %s", t, s); int lens = strlen(s); getFail(s, lens); Matrix ans(lens); for(int i = 0; i < lens; ++i) for(int k = 0; t[k]; ++k){ int j = i; while(j && s[j] != t[k]) j = f[j]; if(s[j] == t[k]) ++j; ++ans.a[i][j]; } ans = fast_pow(ans, n); unsigned int res = 0; for(int i = 0; i < lens; ++i) res += ans.a[0][i]; printf("Case %d: %u\n", kase, res); } return 0; }