传送门
f[i][j] 表示 到i走了j步的方案数
因为这里是对称的,所以只考虑上半边
![f[A][i]=2*f[B][i-1] 公交车路线[矩阵乘法优化DP]_c++_02](https://file.cfanz.cn/uploads/gif/2022/07/12/8/Pd2F08Rb28.gif)
![f[B][i]=f[A][i-1]+f[C][i-1] 公交车路线[矩阵乘法优化DP]_i++_03](https://file.cfanz.cn/uploads/gif/2022/07/12/8/7AU5I7aYWd.gif)
![f[D][i]=f[C][i-1] 公交车路线[矩阵乘法优化DP]_c++_05](https://file.cfanz.cn/uploads/gif/2022/07/12/8/aC7P478AU1.gif)
![f[1][0]=1 公交车路线[矩阵乘法优化DP]_矩阵乘法_06](https://file.cfanz.cn/uploads/gif/2022/07/12/8/dc2cbf686R.gif)
考虑矩阵乘法优化
发现矩阵为
0 1 0 0
2 0 1 0
0 1 0 1
0 0 1 0
#include<bits/stdc++.h>
#define Mod 1000
using namespace std;
struct Matrix{
int x[5][5];
Matrix(){memset(x,0,sizeof(x));}
}; int n;
Matrix mul(Matrix a,Matrix b){
Matrix c;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
for(int k=1;k<=4;k++)
c.x[i][j] = (c.x[i][j] + a.x[i][k] * b.x[k][j]) % Mod;
return c;
}
Matrix power(Matrix a,int k){
Matrix ans;
for(int i=1;i<=4;i++) ans.x[i][i]=1;
for(;k;k>>=1){
if(k&1) ans = mul(ans,a);
a = mul(a,a);
}return ans;
}
int main(){
scanf("%d",&n); Matrix a,b;
a.x[1][1]=1;
b.x[1][2]=1 , b.x[2][1]=2 , b.x[2][3]=1;
b.x[3][2]=1 , b.x[3][4]=1 , b.x[4][3]=1;
b = power(b,n-1); a = mul(a,b);
int ans = a.x[1][4] * 2; printf("%d",ans%Mod); return 0;
}










