把fm看成01,f-1,m-0;
不能存在101,111;
dp[i]代表第i结尾的方案数;
①:结尾是0一定行:只要i-1序列里添个0就好了,dp[i]+=dp[i-1];
②:结尾是1
如果***10或者***11的序列,加上1就不行;
那我扩大,01或者11,很明显s[n-3]==1就不行,
再扩大,/101/111/011/001,只有001一定行,所以就是dp[i-3]后面加个001就好了,dp[i]+=dp[i-3];
③:结尾为1,再扩大;
0001/0011/0101/0111/1001/1011/1101/1111/ 0001已经被第二种情况包括了,所以只有0011,那么就是dp[i-4]后面加个0011就好了;
之后再扩大,会发现没有啦~之前所有的情况都包括了;
所以dp[i]=dp[i-1]+dp[i-3]+dp[i-4];
跑一发矩阵快速幂就好了;
矩阵:
1 0 1 1
1 0 0 0
0 1 0 0
0 0 1 0
#include <bits/stdc++.h> using namespace std; typedef long long LL; int mod; int n; struct asd{ int num[4][4]; }; asd mul(asd a,asd b) { asd ans; memset(ans.num,0,sizeof(ans.num)); for(int i=0;i<4;i++) for(int j=0;j<4;j++) for(int k=0;k<4;k++) ans.num[i][j]=(ans.num[i][j]+a.num[i][k]*b.num[k][j]%mod)%mod; return ans; } asd quickmul(int g,asd x) { asd ans; for(int i=0;i<4;i++) for(int j=0;j<4;j++) { if(i==j) ans.num[i][j]=1; else ans.num[i][j]=0; } while(g) { if(g%2) ans=mul(ans,x); x=mul(x,x); g>>=1; } return ans; } int main() { while(~scanf("%d%d",&n,&mod)) { if(n<=4) { if(n==0) printf("0 "); else if(n==1) printf("%d ",2%mod); else if(n==2) printf("%d ",4%mod); else if(n==3) printf("%d ",6%mod); else if(n==4) printf("%d ",9%mod); continue; } asd tmp; // 1 0 1 1 // 1 0 0 0 // 0 1 0 0 // 0 0 1 0 tmp.num[0][0]=1;tmp.num[0][1]=0;tmp.num[0][2]=1;tmp.num[0][3]=1; tmp.num[1][0]=1;tmp.num[1][1]=0;tmp.num[1][2]=0;tmp.num[1][3]=0; tmp.num[2][0]=0;tmp.num[2][1]=1;tmp.num[2][2]=0;tmp.num[2][3]=0; tmp.num[3][0]=0;tmp.num[3][1]=0;tmp.num[3][2]=1;tmp.num[3][3]=0; asd ans=quickmul(n-4,tmp); printf("%d ",(ans.num[0][0]*9%mod+ans.num[0][1]*6%mod+ans.num[0][2]*4%mod+ans.num[0][3]*2%mod)%mod); } return 0; }