面试题9(变形):跳台阶
题目链接:http://ac.jobdu.com/problem.php?pid=1388
思路:设青蛙跳上一个n级的台阶总共有Fn种跳法,显然达到n级台阶最后一步有两种方式
1、从第n-1级台阶跳一步
2、从第n-2级台阶跳两步
可得出递推公式:Fn = Fn-1 + Fn-2 斐波那契数列,只不过前两项为1,2
code:
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 const int M = 2; 5 const int MOD = 1000000007; 6 typedef long long LL; 7 LL ans[M][M]; 8 LL tmp[M][M]; 9 10 // 矩阵乘法 11 void matrixMul(LL mat1[M][M], LL mat2[M][M]) 12 { 13 LL mat3[M][M]; 14 for (int i = 0; i < M; ++i) 15 { 16 for (int j = 0; j < M; ++j) 17 { 18 mat3[i][j] = 0; 19 for (int k = 0; k < M; ++k) 20 mat3[i][j] += mat1[i][k] * mat2[k][j]; 21 } 22 } 23 memcpy(mat1, mat3, sizeof(mat3)); 24 } 25 26 // 矩阵快速幂 27 void matrixQuickMod(int n) 28 { 29 tmp[0][0] = 1; 30 tmp[0][1] = 1; 31 tmp[1][0] = 1; 32 tmp[1][1] = 0; 33 34 // 将ans处理成单位矩阵 35 memset(ans, 0, sizeof(ans)); 36 for (int i = 0; i < M; ++i) ans[i][i] = 1; 37 38 while (n) 39 { 40 if (n & 1) matrixMul(ans, tmp); // 当n为奇数时,跟新ans 41 n >>= 1; 42 matrixMul(tmp, tmp); // 当n为偶数时跟新tmp 43 } 44 } 45 46 int main() 47 { 48 int n; 49 while (scanf("%d", &n) != EOF) 50 { 51 matrixQuickMod(n); 52 printf("%lld\n", ans[0][0]); 53 } 54 return 0; 55 }