zoukankan      html  css  js  c++  java
  • 面试题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
    ", ans[0][0]);
    53     }
    54     return 0;
    55 }
  • 相关阅读:
    软件构架 课堂练习一
    《软件构架实践》阅读笔记06
    《软件构架实践》阅读笔记05
    《软件构架实践》阅读笔记04
    接口如何实现多态
    c++虚函数的作用是什么?
    java中修饰符作用范围
    Servlet生命周期
    ERP理解
    内部类和匿名内部类
  • 原文地址:https://www.cnblogs.com/ykzou/p/4443707.html
Copyright © 2011-2022 走看看