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

传送门

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

f[i][j]=f[i-1][j-1]+f[i+1][j-1] 

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

f[A][i]=2*f[B][i-1]

f[B][i]=f[A][i-1]+f[C][i-1]

f[C][i]=f[B][i-1]+f[D][i-1] 

f[D][i]=f[C][i-1]

f[1][0]=1

考虑矩阵乘法优化

发现矩阵为

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

猜你喜欢

转载自blog.csdn.net/sslz_fsy/article/details/84779704