[SSL1531] Fibonacci Sequence IV [Matrix Multiplication]

Insert picture description here

analysis

Consider a 1×4 matrix [f [n − 2], f [n − 1], n, 1] [f[n-2],f[n-1],n,1]f[n2],f[n1],n,1 ] , I hope to find a 4×4 matrix A, so that this 1×4 matrix is ​​multiplied by A to get the matrix:
[f [n − 1], f [n], n + 1, 1] = [f [ n − 1], f [n − 1] + f [n − 2] + n + 1, n + 1, 1】 【f[n-1],f[n],n+1,1】=【 f[n-1],f[n-1]+f[n-2]+n+1,n+1,1】f[n1],f[n],n+1,1f[n1],f[n1]+f[n2]+n+1,n+1,1 ] It is
easy to construct this 4×4 matrix A, that is,
Insert picture description here
as long as the construction matrix is ​​multiplied every time, it can have a recursive effect.

Upload code

#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=4;st.m=4;
	st.f[1][1]=0;st.f[1][2]=1;st.f[1][3]=0;st.f[1][3]=0;
	st.f[2][1]=1;st.f[2][2]=1;st.f[2][3]=0;st.f[1][3]=0;
	st.f[3][1]=0;st.f[3][2]=1;st.f[3][3]=1;st.f[1][3]=0;
	st.f[4][1]=0;st.f[4][2]=1;st.f[4][3]=1;st.f[4][4]=1;
	if(n<=3)
	{
    
    
		cout<<1;
		return 0;
	}
	else
	{
    
    
		B.m=4;B.n=1;
		B.f[1][1]=1;B.f[1][2]=1;B.f[1][3]=3;B.f[1][4]=1;
		ksm(n-1);
		B=B*A;
		cout<<B.f[1][1];
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/dglyr/article/details/111750362