矩阵快速幂模板(以斐波那契数列为例)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int mod = 1e9+7;
 5 struct Matrix {
 6   int a[3][3];
 7   Matrix() { memset(a, 0, sizeof a); }
 8   Matrix operator*(const Matrix &b) const {//重载矩阵乘法 
 9     Matrix res;
10     for (int i = 1; i <= 2; ++i)
11       for (int j = 1; j <= 2; ++j)
12         for (int k = 1; k <= 2; ++k)
13           res.a[i][j] = (res.a[i][j] + a[i][k] * b.a[k][j]) % mod;
14     return res;
15   }
16 }ans,base;//初始矩阵ans,乘法矩阵base 
17 
18 void init() {
19   base.a[1][1] = base.a[1][2] = base.a[2][1] = 1;
20   ans.a[1][1] = ans.a[1][2] = 1;
21 }
22 
23 void qpow(int b) {//矩阵快速乘 
24   while (b) {
25     if (b & 1) ans = ans * base;
26     base = base * base;
27     b >>= 1;
28   }
29 }
30 
31 int main() {
32   int n;scanf("%d",&n);
33   if (n <= 2) return puts("1"), 0;
34   init();
35   qpow(n - 2);
36   printf("%d",ans.a[1][1] % mod);//ans.a[1][1]为F(n) 
37 }

 

posted @ 2020-02-03 19:16  AaronChang  阅读(151)  评论(0编辑  收藏  举报