P1962斐波那契数列

矩阵快速幂加速递推

时间复杂度O(2^3logn)

#include<bits/stdc++.h>
#define endl '\n'
#define int int64_t
using namespace std;
const int mod = 1e9 + 7;
struct matrix {
	int c[4][4];
	matrix() { memset(c, 0, sizeof(c)); }
}res;
matrix operator*(matrix& a,matrix& b) {
	matrix t;
	for (int i = 1; i <= 2; ++i)
		for (int j = 1; j <= 2; ++j)
			for (int k = 1; k <= 2; ++k)
			  t.c[i][j] = (t.c[i][j] + a.c[i][k] * b.c[k][j]) % mod;
	return t;
}
void qpow(matrix& a,int b) {
	for (int i = 1; i <= 2;++i)res.c[i][i] = 1;
	while (b) {
		if (b & 1)res = res * a;
		a = a * a, b >>= 1;
	}
}
signed main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	matrix a; a.c[1][1] = 1, a.c[1][2] = 1, a.c[2][1] = 1, a.c[2][2] = 0;
	int n; cin >> n;
	if (n == 1) { cout << 1 << endl; return 0; }
	qpow(a, n - 2);
	int f1, f2;f1 = f2 = 1;
	cout << (f1 * res.c[1][1] + f2 * res.c[2][1]) % mod << endl;
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值