Description
l个人排队,f表示女,m表示男,包含子串‘fmf’和‘fff’的序列为O队列,否则为E队列,有多少个序列为E队列,结果模m
Input
多组输入,每组用例占一行包括两个整数l和m分别表示队列长度和模数,以文件尾结束输入
Output
对于每组用例,输出E队列的数量(结果模m)
Sample Input
3 8
4 7
4 8
Sample Output
6
2
1
Solution
用f(n)来表示序列长度为n时E序列的数量,一步步往前推可以发现下列关系
一.当第n位是m时,只要前面n-1位是E序列,加上m还是E序列,所以f(n)+=f(n-1)
二.当第n位是f时,第n-1位有两种情况m和f
1.当第n-1位是m时,第n-2位只能为m,而只要前n-3位是E序列,那么加上mmf一定也是E序列,所以f(n)+=f(n-3)
2.当第n-1位是f时,第n-2位只能是m,且第n-3位只能是m,而只要前n-4位是E序列,那么加上mmff一定也是E序列,所以f(n)+=f(n-4)
综合上面的分析可以得到转移方程f(n)=f(n-1)+f(n-3)+f(n-4)
显然用这个转移方程直接算时间复杂度较高,可以用矩阵加速,轻易得出转移矩阵
剩下只需用套矩阵快速幂模板即可,注意l=0,1,2,3,4时特判
Code
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 5
typedef long long ll;
struct Mat
{
int mat[maxn][maxn];//矩阵
int row,col;//矩阵行列数
};
Mat mod_mul(Mat a,Mat b,int p)//矩阵乘法
{
Mat ans;
ans.row=a.row;
ans.col=b.col;
memset(ans.mat,0,sizeof(ans.mat));
for(int i=0;i<ans.row;i++)
for(int k=0;k<a.col;k++)
if(a.mat[i][k])
for(int j=0;j<ans.col;j++)
{
ans.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
ans.mat[i][j]%=p;
}
return ans;
}
Mat mod_pow(Mat a,int k,int p)//矩阵快速幂
{
Mat ans;
ans.row=a.row;
ans.col=a.col;
for(int i=0;i<a.row;i++)
for(int j=0;j<a.col;j++)
ans.mat[i][j]=(i==j);
while(k)
{
if(k&1)ans=mod_mul(ans,a,p);
a=mod_mul(a,a,p);
k>>=1;
}
return ans;
}
int main()
{
int l,m;
while(~scanf("%d%d",&l,&m))
{
//l<=4时特判
if(l==0)printf("0\n");
else if(l==1)printf("%d\n",2%m);
else if(l==2)printf("%d\n",4%m);
else if(l==3)printf("%d\n",6%m);
else if(l==4)printf("%d\n",9%m);
else
{
Mat A,B,ans;
//构造转移矩阵A
A.row=A.col=4;
memset(A.mat,0,sizeof(A.mat));
A.mat[0][0]=A.mat[0][2]=A.mat[0][3]=A.mat[1][0]=A.mat[2][1]=A.mat[3][2]=1;
//构造原始矩阵B
B.row=4,B.col=1;
B.mat[0][0]=9,B.mat[1][0]=6,B.mat[2][0]=4,B.mat[3][0]=2;
ans=mod_pow(A,l-4,m);//矩阵快速幂
ans=mod_mul(ans,B,m);//A^(n-4)*B即为答案
printf("%d\n",ans.mat[0][0]);
}
}
return 0;
}