[POJ 3070] Fibonacci【矩乘优化】
Problem:
Time Limit: 1000MS | Memory Limit: 65536K |
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
0 9 999999999 1000000000 -1
Sample Output
0 34 626 6875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
Source
Solution:
很经典的矩乘优化题,而且出题人很良心地给出了解题思路和温馨提示~~
如果直接暴力递推 Fibonacci 数列的第 n 项,时间复杂度为 O(Tn),显然 TLE 炸上天。。
You're too young ~~ too simple ~~ too naive ~~
所以引入一种高大上的优化方法,也就是出题人告诉我们的公式 2。
我们只要先模拟矩阵乘法(不知道矩阵乘法?点此速成 .(i_i).),再写一个快速幂就行了。
Code: O(Ts3logn), s为矩阵阶数(=2) [144K, 16MS]
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<cassert> #include<iostream> #include<algorithm> using namespace std; const int MOD = 10000; int n; struct Matrix{ int ele[3][3], size; inline void setIdentity(int idensize){ memset(ele, 0, sizeof(ele)); size = idensize; for(register int i = 1; i <= size; i++) ele[i][i] = 1; } inline Matrix operator * (const Matrix &mat2) const { assert(size == mat2.size); // Or the multiplication isn't defined Matrix res; res.size = size; for(register int i = 1; i <= size; i++) for(register int j = 1; j <= mat2.size; j++){ res.ele[i][j] = 0; for(register int k = 1; k <= size; k++) res.ele[i][j] = (res.ele[i][j] + ele[i][k] * mat2.ele[k][j]) % MOD; } return res; } inline Matrix pow(int ex){ Matrix bas = *this, res; res.setIdentity(size); while(ex){ if(ex & 1) res = res * bas; ex >>= 1, bas = bas * bas; } return res; } } Fib; int main(){ while(scanf("%d", &n) != EOF && n != -1){ if(n < 2){ if(n) puts("1"); else puts("0"); continue; } Fib.size = 2; Fib.ele[1][1] = 1, Fib.ele[1][2] = 1; Fib.ele[2][1] = 1, Fib.ele[2][2] = 0; Fib = Fib.pow(n - 1); printf("%d\n", Fib.ele[1][1]); } return 0; }
发表评论