[SSL2513] Kindergarten Math Problem I [Matrix Multiplication]

Insert picture description here
Insert picture description here

analysis

The law of violence
is actually a bit incomplete. . .
But seeing the root number 5 comes to mind the Fibonacci general term formula.
The
original formula of Baidu Encyclopedia is as follows:
Insert picture description here
Then just do it directly according to the Fibonacci matrix multiplication.
like this

Upload code

/*斐波那契通项公式*/ 
#include<iostream>
#include<cstdio>
#include<algorithm> 
using namespace std;
typedef long long ll;
ll n;
const int mod=1000000007;
struct matrix
{
    
    
	ll n,m;
	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)
{
    
    
	x--;
	A=st;
	while(x)
	{
    
    
		if(x&1) A=A*st;
		st=st*st;
		x>>=1;
    }
}

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

Guess you like

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