[SSL1529] Fibonacci Sequence II [Matrix Multiplication]

Insert picture description here

analysis

Consider a 1×2 matrix [f[n-2], f[n-1]]. According to the recurrence relation of the fibonacci sequence, we hope to obtain the matrix [f[n-1],f[n]]=[f[n-1],f[n-1] by multiplying by a 2×2 matrix +f[n-2]] It is easy to construct this 2×2 matrix A, namely:
Insert picture description here

Therefore, there are [f [1], f [2]] × A = [f [2], f [3]] [f[1], f[2]] × A = [f[2], f[ 3]】f[1],f[2]×Af[2],f [ 3 ] Because matrix multiplication satisfies the associative law, there are:[f [1], f [2]】 × A n − 1 = [f [n], f [n + 1]】 【f[1 ],f[2]】×A n-1=【f[n],f[n+1]】f[1],f[2]×An1=f[n],f[n+1 ]
The first element of this matrix is ​​what you want.

Upload code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int mod=10000;
ll n;

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

Guess you like

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