Now we define that ‘f’ is short for female and ‘m’ is short for male. If the queue’s length is L, then there are 2L numbers of queues. For example, if L = 2, then they are ff, mm, fm, mf . If there exists a subqueue as fmf or fff, we call it O-queue else it is a E-queue.
Your task is to calculate the number of E-queues mod M with length L by writing a program.
#include
#include
using namespace std;
int n,mod;
struct Matrix{
int arr[4][4];
};
Matrix unit,init;
//矩阵相乘的函数
Matrix Mul(Matrix a,Matrix b){
Matrix c;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){
c.arr[i][j]=0;
for(int k=0;k<4;k++)
c.arr[i][j]=(c.arr[i][j]+a.arr[i][k]*b.arr[k][j]%mod)%mod;
//cout<<c.arr[i][j]<<endl;
c.arr[i][j]%=mod;
}
return c;
}
//进行F[n]=F[n-1]+F[n-3]+F[n-4]
Matrix Pow(Matrix a,Matrix b,int k){
while(k){
if(k&1){
b=Mul(b,a);
}
a=Mul(a,a);
//cout<<k<<endl;
k>>=1;//k/=2但是前者快点
}
return b;
}
//初始化
void Init(){
for(int i=0;i<4;i++)
for(int j=0;j<4;j++){
init.arr[i][j]=0;
unit.arr[i][j]=0;
}
//递推的前四项
unit.arr[0][0]=9, unit.arr[0][1]=6, unit.arr[0][2]=4, unit.arr[0][3]=2;
//设置递推关系的矩阵
init.arr[0][0]=1, init.arr[0][1]=1, init.arr[1][2]=1, init.arr[2][0]=1,
init.arr[2][3]=1, init.arr[3][0]=1;
}
int main(){
while(~scanf("%d%d",&n,&mod)){
if(n<=4){
if(n==0)
printf("0");
else if(n==1)
printf("%d\n",2%mod);
else if(n==2)
printf("%d\n",4%mod);
else if(n==3)
printf("%d\n",6%mod);
else if(n==4)
printf("%d\n",9%mod);
continue;
}
Matrix res=Pow(init,unit,n-4);
printf("%d\n",res.arr[0][0]%mod);
}
return 0;
}