斐波那契數列Ⅳ【矩陣乘法】

ssl_fuyang發表於2020-12-12

>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;
}

相關文章