题目链接
给一个长度为n的字符串, 每个字符可以使f或m。 问你不包含子串fmf以及fff的字符串数量有多少。
令0表示mm结尾, 1表示mf, 2表示ff, 3表示fm。
那么
f(n+1, 0) = f(n, 0) + f(n, 3)
f(n+1, 1) = f(n, 0)
f(n+1, 2) = f(n, 1)
f(n+1, 3) = f(n, 1) + f(n, 2)
所以构造出矩阵
{1, 0, 0, 1}
{1, 0, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 0}
然后快速幂, 最后的答案就是矩阵第一列的值相加。
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <complex>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef complex <double> cmx;
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int a[4][4] = {
{1, 0, 0, 1},
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 1, 1, 0},
};
int mod;
struct Matrix
{
int f[4][4];
Matrix() {
mem(f);
}
}m;
Matrix operator * (Matrix a, Matrix b) {
Matrix c;
for(int k = 0; k<4; k++) {
for(int j = 0; j<4; j++) {
for(int i = 0; i<4; i++) {
c.f[i][j] += a.f[i][k]*b.f[k][j];
c.f[i][j] %= mod;
}
}
}
return c;
}
Matrix operator ^(Matrix a, ll b) {
Matrix tmp;
for(int i = 0; i<4; i++)
tmp.f[i][i] = 1;
while(b) {
if(b&1)
tmp = tmp*a;
a = a*a;
b>>=1;
}
return tmp;
}
int main()
{
int n;
while(cin>>n>>mod) {
memcpy(m.f, a, sizeof(a));
m = m^n;
int ans = 0;
for(int i = 0; i < 4; i++) {
ans = (ans + m.f[i][0])%mod;
}
cout<<ans<<endl;
}
return 0;
}