An alternative formula for the Fibonacci sequence is
.
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:
.
思路——题目已经告诉我们用矩阵连乘求Fibonacci数,问题是n很大,如果直接矩阵乘n-1次,肯定TLE。因此我们可以用二分求快速幂:
复杂度分析——时间复杂度:O(n),空间复杂度:O(1)
附上AC代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned int UI;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
const double PI = 3.14159265;
const double E = 2.71828182846;
const int MOD = 10000;
struct matrix
{
int mat[2][2];
} res, base; // 定义一个结构体封装矩阵
matrix mul(matrix a, matrix b); // 矩阵乘法运算
int fast_mod(int x); // 二分求快速幂
// a^n = (a^(n/2))^2 当n为偶数
// a^n = a*(a^(n/2))^2 当n为奇数
int main()
{
ios::sync_with_stdio(false);
int num;
while (cin >> num && num != -1)
{
cout << fast_mod(num) << endl;
}
return 0;
}
matrix mul(matrix a, matrix b)
{
matrix temp;
for (int i=0; i<2; ++i)
for (int j=0; j<2; ++j)
{
temp.mat[i][j] = 0;
for (int k=0; k<2; ++k)
temp.mat[i][j] = (temp.mat[i][j]+a.mat[i][k]*b.mat[k][j])%MOD;
}
return temp;
}
int fast_mod(int x)
{
base.mat[0][0]=base.mat[0][1]=base.mat[1][0]=1;
base.mat[1][1]=0; // 原始矩阵
res.mat[0][0]=res.mat[1][1]=1;
res.mat[0][1]=res.mat[1][0]=0; // 单位矩阵
while (x)
{
if (x & 1) // 相当于模2
{
res = mul(res, base);
}
base = mul(base, base);
x >>= 1; // 相当于除2
}
return res.mat[0][1];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/silenceneo/article/details/47620097