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

>Link

ssl 1531


>Description

f n = f n − 1 + f n − 2 + n + 1 f_n=f_{n-1}+f_{n-2}+n+1 fn=fn1+fn2+n+1 的第 N N N项,其中 f 1 = f 2 = 1 f_1=f_2=1 f1=f2=1


>解题思路

这道题仍然是矩阵乘法例题,思路同斐波那契数列Ⅱ斐波拉契数列Ⅲ

打题解打得不想说话了╥﹏╥
A A A矩阵为 [ 1 1 3 1 ] \begin{bmatrix} 1 &1 &3 &1 \end{bmatrix} [1131]

B B B矩阵为 [ 0 1 0 0 1 1 0 0 0 1 1 0 0 1 1 1 ] \begin{bmatrix} 0 &1 &0 &0 \\ 1 & 1 &0 &0 \\ 0& 1& 1& 0\\ 0 & 1 & 1 & 1 \end{bmatrix} 0100111100110001


>代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;

const LL p = 9973;
struct matrix
{
    
    
	int x, y;
	LL a[10][10];
} A, B, ans;
LL n;

matrix operator *(matrix a, matrix b)
{
    
    
	matrix c;
	c.x = a.x, c.y = b.y;
	for (int i = 1; i <= c.x; i++)
	  for (int j = 1; j <= c.y; j++) c.a[i][j] = 0;
	for (int k = 1; k <= a.y; k++)
	  for (int i = 1; i <= a.x; i++)
	    for (int j = 1; j <= b.y; j++)
	      c.a[i][j] = (c.a[i][j] + a.a[i][k] * b.a[k][j] % p) % p;
	return c;
}
void power (LL k)
{
    
    
	if (k == 1) {
    
    B = A; return;}
	power (k >> 1);
	B = B * B;
	if (k & 1) B = B * A;
}

int main()
{
    
    
	scanf ("%lld", &n);
	if (n == 1 || n == 2) {
    
    printf ("1"); return 0;}
	A.x = A.y = 4;
	A.a[1][1] = A.a[1][3] = A.a[1][4] = A.a[2][3] = 0;
	A.a[2][4] = A.a[3][1] = A.a[3][4] = A.a[4][1] = 0;
	A.a[1][2] = A.a[2][1] = A.a[2][2] = A.a[3][2] = 1;
	A.a[3][3] = A.a[4][2] = A.a[4][3] = A.a[4][4] = 1;
	power (n - 1);
	ans.x = 1, ans.y = 4;
	ans.a[1][1] = ans.a[1][2] = ans.a[1][4] = 1;
	ans.a[1][3] = 3;
	ans = ans * B;
	printf ("%lld", ans.a[1][1]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43010386/article/details/111063633
今日推荐