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

    你可能感兴趣的文章
    NoSQL&MongoDB
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    NPM使用前设置和升级
    查看>>
    npm入门,这篇就够了
    查看>>
    npm切换到淘宝源
    查看>>
    npm前端包管理工具简介---npm工作笔记001
    查看>>
    npm发布自己的组件UI包(详细步骤,图文并茂)
    查看>>
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>