洛谷P1962 斐波那契数列 (矩阵快速幂)
学了矩阵,练一下手。。。
1 #include <bits/stdc++.h> 2 #define ll long long 3 using namespace std; 4 const int mod = 1e9 + 7; 5 struct Matrix { 6 ll g[3][3]; 7 Matrix() { 8 memset(g, 0, sizeof(g)); 9 } 10 Matrix operator * (const Matrix &b) const { 11 Matrix res; 12 for (int i = 1; i <= 2; i ++) 13 for (int j = 1; j <= 2; j ++) 14 for (int k = 1; k <= 2; k ++) 15 res.g[i][k] = (res.g[i][k] + g[i][j] * b.g[j][k] % mod) % mod; 16 return res; 17 } 18 }a, ans; 19 void init() { 20 a.g[1][1] = 1, a.g[1][2] = 1, a.g[2][1] = 1; 21 ans.g[1][1] = ans.g[1][2] = 1; 22 } 23 void qpow(ll x) { 24 while (x) { 25 if (x & 1) ans = ans * a; 26 a = a * a; 27 x >>= 1; 28 } 29 } 30 int main() { 31 ll n; cin >> n; 32 if (n <= 2) {cout << 1; return 0;} 33 init(); 34 qpow(n - 2); 35 cout << ans.g[1][1] % mod; 36 return 0; 37 }