SDNU 1062.Fibonacci

1062.Fibonacci

Time Limit: 1000 MS Memory Limit: 32768 KB
Total Submission(s): 148 Accepted Submission(s): 69

Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2.

Input
a single line containing n (where 0 ≤ n ≤ 100,000,000,000)

Output
print Fn mod 1000000007 in a single line.

Sample Input
99999999999

Sample Output
669753982

Hint
An alternative formula for the Fibonacci sequence is
Alt text
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
Alt text
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
Alt text

题解:
题意就是输出斐波那契数列里 n 位的值 mod 1000000007。
这是一道矩阵快速幂的模板题,不会矩阵快速幂的可以看下面的博客,写的挺清楚的。(注:矩阵快速幂需要矩阵这个前置技能)
注意 n == 0 的情况。
矩阵快速幂

Ac代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int N = 2;
long long tmp[N][N];
long long res[N][N];

void multi(long long a[][N],long long b[][N])
{
memset(tmp,0,sizeof tmp);
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
for(int k = 0; k < N; k++)
{
tmp[i][j] += a[i][k] * b[k][j] % 1000000007;
}
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
a[i][j] = tmp[i][j];
}
}
}

void Pow(long long a[][N],long long n)
{
memset(res,0,sizeof res);
for(int i = 0; i < N; i++)
res[i][i] = 1;
while(n)
{
if(n & 1)
multi(res,a);
multi(a,a);
n >>= 1;
}
}


int main()
{
long long n;
while(cin >> n)
{
if(n == 0)
{
cout << 0 << '\n';
continue;
}
long long a[N][N] = {1,1,1,0};
Pow(a,n - 1);
cout << res[0][0] % 1000000007 << '\n';
}
}
我好饿呀!求打赏!