洛谷 P1962 斐波那契数列
Description
大家都知道,斐波那契数列是满足如下性质的一个数列:
• f(1) = 1
• f(2) = 1
• f(n) = f(n-1) + f(n-2) (n ≥ 2 且 n 为整数)
请你求出 f(n) mod 1000000007 的值。
Input
- 第 1 行:一个整数 n
Output
- 第 1 行: f(n) mod 1000000007 的值
Sample Input
10
Sample Output
55
Data Size
对于 100% 的数据: n在long long(INT64)范围内。
题解:
- 矩阵加速。写这题前务必看过这篇
- 推导过程:
#include <iostream>
#include <cstdio>
#include <cstring>
#define mod 1000000007
#define LL long long
using namespace std;
struct Obj
{
LL m[3][3];
Obj() {memset(m, 0, sizeof(m));}
};
LL n;
Obj mul(Obj a, Obj b)
{
Obj c;
for(LL i = 1; i <= 2; i++)
for(LL j = 1; j <= 2; j++)
for(LL k = 1; k <= 2; k++)
c.m[i][j] += (a.m[i][k] % mod * b.m[k][j] % mod) % mod,
c.m[i][j] %= mod;
return c;
}
Obj power(Obj a, LL b)
{
Obj d; d.m[1][1] = d.m[2][2] = 1;
Obj r = d, base = a;
while(b)
{
if(b & 1) r = mul(r, base);
base = mul(base, base);
b >>= 1;
}
return r;
}
int main()
{
cin >> n;
if(n <= 2) {cout << 1; return 0;}
Obj t1; t1.m[1][1] = t1.m[1][2] = t1.m[2][1] = 1; //系数矩阵
Obj ans = power(t1, n - 2);
Obj t2; t2.m[1][1] = t2.m[2][1] = 1; //初始矩阵
Obj t3; //结果矩阵
for(LL i = 1; i <= 2; i++)
for(LL j = 1; j <= 1; j++)
for(LL k = 1; k <= 2; k++)
t3.m[i][j] += (ans.m[i][k] % mod * t2.m[k][j] % mod) % mod,
t3.m[i][j] %= mod;
cout << t3.m[1][1];
return 0;
}