博客
关于我
sdnu1085.爬楼梯再加强版(矩阵快速幂)
阅读量:273 次
发布时间:2019-03-01

本文共 1516 字,大约阅读时间需要 5 分钟。

为了解决这个问题,我们需要计算上楼梯的方式总数。WZ一步可以迈一阶、两阶或者三阶,给定楼梯的阶数N,我们需要计算总共有多少种上楼的方式,并输出结果模1000000007。

方法思路

这个问题可以通过递推关系和矩阵快速幂来解决。递推关系为f(n) = f(n-1) + f(n-2) + f(n-3),其中f(0) = 1,f(1) = 1,f(2) = 2。为了高效计算大数的情况,我们使用矩阵快速幂方法,将递推关系转化为矩阵乘法的形式,然后利用快速幂算法来计算结果。

解决代码

#include 
using namespace std;const int MOD = 1000000007;const int N = 3;struct mat { ll a[N][N];};mat mat_mul(mat x, mat y) { mat res; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { res.a[i][j] = (x.a[i][0] * y.a[0][j] + x.a[i][1] * y.a[1][j] + x.a[i][2] * y.a[2][j]) % MOD; } } return res;}ll mat_pow(mat c, ll power) { mat res = { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }; while (power > 0) { if (power % 2 == 1) { res = mat_mul(res, c); } c = mat_mul(c, c); power /= 2; } return res.a[0][0];}int main() { long long n; while (scanf("%lld", &n) != EOF) { if (n == 1) { cout << 1 << endl; } else if (n == 2) { cout << 2 << endl; } else if (n == 3) { cout << 4 << endl; } else { mat A = { {1, 1, 1}, {1, 0, 0}, {0, 1, 0} }; mat C = mat_pow(A, n - 3); long long ans = (4 * C.a[0][0] + 2 * C.a[0][1] + C.a[0][2]) % MOD; cout << ans << endl; } } return 0;}

代码解释

  • 矩阵定义和乘法函数:定义了矩阵的结构和矩阵乘法函数mat_mul,用于矩阵的快速幂计算。
  • 矩阵快速幂函数mat_pow函数用于计算矩阵的高次幂,通过快速幂算法将复杂度降低到O(logN)。
  • 主函数:读取输入值N,处理特殊情况(N=1, 2, 3),并使用矩阵快速幂计算结果。结果输出后,模1000000007。
  • 这种方法能够高效处理非常大的N值,确保在合理时间内完成计算。

    转载地址:http://usio.baihongyu.com/

    你可能感兴趣的文章
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>