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

本文共 1559 字,大约阅读时间需要 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/

    你可能感兴趣的文章
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    node exporter完整版
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node 裁切图片的方法
    查看>>
    Node+Express连接mysql实现增删改查
    查看>>
    node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
    查看>>