博客
关于我
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/

    你可能感兴趣的文章
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>