poj3070(矩阵快速幂)
题目链接:http://poj.org/problem?id=3070
1 #include <cstdio> 2 #include <iostream> 3 using namespace std; 4 const int MOD = 10000; 5 struct matrix 6 { 7 int m[2][2]; 8 }ans, base; 9 10 matrix multi(matrix a, matrix b) 11 { 12 matrix tmp; 13 for(int i = 0; i < 2; ++i) 14 { 15 for(int j = 0; j < 2; ++j) 16 { 17 tmp.m[i][j] = 0; 18 for(int k = 0; k < 2; ++k) 19 tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD; 20 } 21 } 22 return tmp; 23 } 24 int fast_mod(int n) // 求矩阵 base 的 n 次幂 25 { 26 base.m[0][0] = base.m[0][1] = base.m[1][0] = 1; 27 base.m[1][1] = 0; 28 ans.m[0][0] = ans.m[1][1] = 1; // ans 初始化为单位矩阵 29 ans.m[0][1] = ans.m[1][0] = 0; 30 while(n) 31 { 32 if(n & 1) //实现 ans *= t; 其中要先把 ans赋值给 tmp,然后用 ans = tmp * t 33 { 34 ans = multi(ans, base); 35 } 36 base = multi(base, base); 37 n >>= 1; 38 } 39 return ans.m[0][1]; 40 } 41 42 int main() 43 { 44 int n; 45 while(scanf("%d", &n) && n != -1) 46 { 47 printf("%d\n", fast_mod(n)); 48 } 49 return 0; 50 }