>Link
luogu U145243
>Description
求 f n = f n − 1 + f n − 2 f_n=f_{n-1}+f_{n-2} fn=fn−1+fn−2 序列中前 N N N 项的和,其中 f 1 = f 2 = 1 f_1=f_2=1 f1=f2=1
>解题思路
又一矩阵乘法例题,与斐波那契数列Ⅱ相似
方案一:
设 s n s_n sn为序列中前 N N N项的和,如何推导 s n = f n + 2 − 1 s_n=f_{n+2}-1 sn=fn+2−1:
f n + 2 − 1 = f n + f n + 1 − 1 = f n + f n − 1 + f n = f n + f n − 1 + . . . + f 1 + f 2 − 1 = f n + f n − 1 + . . . + f 1 = s n f_{n+2}-1=f_{n}+f_{n+1}-1=f_{n}+f_{n-1}+f_{n}=f_n+f_{n-1}+...+f_1 +f_2-1=f_n+f_{n-1}+...+f_1=s_n fn+2−1=fn+fn+1−1=fn+fn−1+fn=fn+fn−1+...+f1+f2−1=fn+fn−1+...+f1=sn
∴ s n = f n + 2 − 1 ∴s_n=f_{n+2}-1 ∴sn=fn+2−1
因此求第 n + 2 n+2 n+2项即可
方案二:
普通算法,定义矩阵 A A A转移为
[ f n − 1 f n s n − 1 ] → [ f n f n + 1 ( f n + f n − 1 ) s n ( s n − 1 + f n ) ] \begin{bmatrix} f_{n-1} & f_{n} & s_{n-1} \end{bmatrix} → \begin{bmatrix} f_{n} & f_{n+1}(f_{n}+f_{n-1}) & s_n(s_{n-1}+f_n) \end{bmatrix} [fn−1fnsn−1]→[fnfn+1(fn+fn−1)sn(sn−1+fn)]
∴ ∴ ∴我们把 A A A矩阵设为 [ 1 1 1 ] \begin{bmatrix} 1 &1 &1 \end{bmatrix} [111]
B B B矩阵设为 [ 0 1 0 1 1 1 0 0 1 ] \begin{bmatrix} 0 &1 &0 \\ 1&1 &1 \\ 0&0 &1 \end{bmatrix} ⎣⎡010110011⎦⎤
>代码
方案一:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;
const LL p = 1e9 + 7;
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);
n += 2;
A.x = A.y = 2;
A.a[1][1] = 0, A.a[1][2] = 1;
A.a[2][1] = A.a[2][2] = 1;
power (n - 1);
ans.x = 1, ans.y = 2;
ans.a[1][1] = ans.a[1][2] = 1;
ans = ans * B;
printf ("%lld", ans.a[1][1] - 1);
return 0;
}
方案二:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;
const LL p = 1e9 + 7;
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);
A.x = A.y = 3;
A.a[1][1] = A.a[1][3] = A.a[3][1] = A.a[3][2] = 0;
A.a[1][2] = A.a[2][1] = A.a[2][2] = A.a[2][3] = A.a[3][3] = 1;
power (n - 1);
ans.x = 1, ans.y = 3;
ans.a[1][1] = ans.a[1][2] = ans.a[1][3] = 1;
ans = ans * B;
printf ("%lld", ans.a[1][3]);
return 0;
}