题解:P1962 斐波那契数列
这是一个经典的求斐波那契数列第
如果使用传统方法:
- 递归:时间复杂度
O(2^n) ,不可行。 - 循环:时间复杂度
O(n) ,当n \ge 28 时也不可行。
因此,我们需要使用矩阵乘法。
矩阵乘法表示:
具体的:
其中
通过计算转移矩阵的
代码实现
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
struct node {
long long a[2][2];
node(){
a[0][0] = a[0][1] = a[1][0] = a[1][1] = 0;
}
// 单位矩阵
node i() {
node res;
res.a[0][0] = res.a[1][1] = 1;
res.a[0][1] = res.a[1][0] = 0;
return res;
}
// 斐波那契->矩阵
node fib() {
node res;
res.a[0][0] = 1; res.a[0][1] = 1;
res.a[1][0] = 1; res.a[1][1] = 0;
return res;
}
// 矩阵乘法
node cf(const node& o) const {
node res;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
res.a[i][j] = (res.a[i][j] + a[i][k] * o.a[k][j]) % MOD;
}
}
}
return res;
}
// 矩阵快速幂
node qpow(long long n) {
node r = i();
node b = *this;
while (n > 0) {
if (n & 1) {
r = r.cf(b);
}
b = b.cf(b);
n >>= 1;
}
return r;
}
};
// 计算斐波那契数列第n项
long long fib(long long n) {
if (n <= 2) return 1;
node m;
m = m.fib();
node r = m.qpow(n - 1);
return r.a[0][0] % MOD;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
long long n;
cin >> n;
cout << fib(n);
return 0;
}