【SSL1530】斐波那契数列III【矩阵乘法】

在这里插入图片描述

分析

考虑1×3的矩阵 【 f [ n − 2 ] , f [ n − 1 ] , 1 】 【f[n-2],f[n-1],1】 f[n2],f[n1],1,希望求得某3×3的矩阵A,使得此1×3的矩阵乘以A得到矩阵: 【 f [ n − 1 ] , f [ n ] , 1 】 = 【 f [ n − 1 ] , f [ n − 1 ] + f [ n − 2 ] + 1 , 1 】 【f[n-1],f[n],1】=【f[n-1],f[n-1]+f[n-2]+1,1】 f[n1],f[n],1f[n1],f[n1]+f[n2]+1,1容易构造出这个3×3的矩阵A,即:
在这里插入图片描述
剩下的就是模板了。

上代码

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
ll n;
const int mod=9973;
struct matrix
{
    
    
	ll m,n;
	ll f[20][20];
}st,A,B;

matrix operator *(matrix a,matrix b)
{
    
    
	matrix C;
	C.n=a.n;C.m=b.m;
	for(int i=1;i<=C.n;i++)
    {
    
    
    	for(int j=1;j<=C.m;j++)
    	{
    
    
    		C.f[i][j]=0;
		}
	}
	for(int k=1;k<=a.m;k++)
	{
    
    
		for(int i=1;i<=a.n;i++)
		{
    
    
			for(int j=1;j<=b.m;j++)
			{
    
    
				C.f[i][j]=(C.f[i][j]+a.f[i][k]*b.f[k][j]%mod)%mod;
			}
		}
	}
	return C;
}

void ksm(ll x)
{
    
    
	if(x==1)
	{
    
    
		A=st;
		return;
	}
	ksm(x/2);
	A=A*A;
	if(x&1) A=A*st;
}

int main()
{
    
    
	cin>>n;
	st.n=3;st.m=3;
	st.f[1][1]=0;st.f[1][2]=1;st.f[1][3]=0;
	st.f[2][1]=1;st.f[2][2]=1;st.f[2][3]=0;
	st.f[3][1]=0;st.f[3][2]=1;st.f[3][3]=1;
	if(n<=2)
	{
    
    
		cout<<1;
		return 0;
	}
	else
	{
    
    
		B.m=3;B.n=1;
		B.f[1][1]=1;B.f[1][2]=1;B.f[1][3]=1;
		ksm(n-1);
		B=B*A;
		cout<<B.f[1][1];
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/dglyr/article/details/111749289