(洛谷P1962) 斐波那契数列
![](https://img2024.cnblogs.com/blog/2979640/202402/2979640-20240229142649119-648342716.png)
这样,我们把原来较为复杂的问题转化成了求某个矩阵的幂的问题,这就可以应用快速幂求解了。
1 #include <cstdio> 2 #define MOD 1000000007 3 typedef long long ll; 4 5 struct matrix 6 { 7 ll a1, a2, b1, b2; 8 matrix(ll a1, ll a2, ll b1, ll b2) : a1(a1), a2(a2), b1(b1), b2(b2) {} 9 matrix operator*(const matrix &y) 10 { 11 matrix ans((a1 * y.a1 + a2 * y.b1) % MOD, 12 (a1 * y.a2 + a2 * y.b2) % MOD, 13 (b1 * y.a1 + b2 * y.b1) % MOD, 14 (b1 * y.a2 + b2 * y.b2) % MOD); 15 return ans; 16 } 17 }; 18 19 matrix qpow(matrix a, ll n) 20 { 21 matrix ans(1, 0, 0, 1); //单位矩阵 22 while (n) 23 { 24 if (n & 1) 25 ans = ans * a; 26 a = a * a; 27 n >>= 1; 28 } 29 return ans; 30 } 31 32 int main() 33 { 34 ll x; 35 matrix M(0, 1, 1, 1); 36 scanf("%lld", &x); 37 matrix ans = qpow(M, x - 1); 38 printf("%lld\n", (ans.a1 + ans.a2) % MOD); 39 return 0; 40 }