思路:
可以找到递推公式f(n)= f(n-1)+f(n-3)+f(n-4)
所以可以构造一个四阶的右乘矩阵来实现递推。
详细方法可以参考类似题型:http://blog.csdn.net/wing_wuchen/article/details/74276372
#include <cstdio>
#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
typedef long long int lli;
using namespace std;
int mod;
const int n = 4;
struct mat{
lli ma[n][n];
};
mat operator * (mat &a,mat &b){
mat c;
memset(c.ma,0,sizeof(c.ma));
for(int k=0;k<n;++k){
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
c.ma[i][j] += a.ma[i][k]*(b.ma[k][j] % mod) % mod;
}
}
}
return c;
}
mat qp(mat a,lli k){
mat c;
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
c.ma[i][j] = (i==j);
}
}
for(;k;k>>=1){
if(k&1) c=c*a;
a = a*a;
}
return c;
}
int main(){
int l;
while(~scanf("%d%d",&l,&mod)){
mat a = {1,1,0,0, 0,0,1,0, 1,0,0,1, 1,0,0,0};
mat b = {9,6,4,2, 0,0,0,0, 0,0,0,0, 0,0,0,0};
if(l <= 4){
if(l == 0){
printf("0\n");
continue;
}
printf("%d\n",b.ma[0][4-l]%mod);
continue;
}
else{
a = qp(a,l-4);
b = b * a;
printf("%d\n",b.ma[0][0]%mod);
}
}
}