51Nod 1242 斐波那契数列的第N项(矩阵快速幂)

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 typedef long long LL;
 6 const int maxn = 2;
 7 const LL m = 1000000009;
 8 
 9 struct Matrix
10 {
11     LL v[maxn][maxn];
12 };
13 
14 //矩阵间的乘法
15 Matrix matrix_mul(Matrix A, Matrix B){
16     Matrix ans;
17     for (int i = 0; i < maxn; i++){
18         for (int j = 0; j < maxn; j++){
19             ans.v[i][j] = 0;
20             for (int k = 0; k < maxn; k++){
21                 ans.v[i][j] += (A.v[i][k] * B.v[k][j]) % m;
22             }
23             ans.v[i][j] %= m;
24         }
25     }
26     return ans;
27 }
28 
29 Matrix matrix_pow(Matrix C, LL n){
30     Matrix ans = { 1, 0, 0, 1 };
31     while (n){
32         if (n & 1){
33             ans = matrix_mul(ans, C);
34         }
35         C = matrix_mul(C, C);
36         n >>= 1;
37     }
38     return ans;
39 }
40 
41 int main(){
42     ios::sync_with_stdio(false);
43 
44     LL n;
45     cin >> n;
46     Matrix e = { 1, 0, 1, 0 };
47     Matrix ee = { 1, 1, 1, 0 };
48     Matrix ans = matrix_pow(ee, n - 1);
49     ans = matrix_mul(e, ans);
50     cout << ans.v[0][0] << endl;
51     //system("pause");
52     return 0;
53 }

 

posted @ 2018-04-16 20:38  ouyang_wsgwz  阅读(123)  评论(0编辑  收藏  举报