0
点赞
收藏
分享

微信扫一扫

公交车路线[矩阵乘法优化DP]

​​传送门​​

f[i][j] 表示 到i走了j步的方案数 

公交车路线[矩阵乘法优化DP]_矩阵乘法 

因为这里是对称的,所以只考虑上半边

公交车路线[矩阵乘法优化DP]_c++_02

公交车路线[矩阵乘法优化DP]_i++_03

公交车路线[矩阵乘法优化DP]_i++_04 

公交车路线[矩阵乘法优化DP]_c++_05

公交车路线[矩阵乘法优化DP]_矩阵乘法_06

考虑矩阵乘法优化

发现矩阵为

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;
}

 


举报

相关推荐

0 条评论