Description
已知一个楼梯有n级,小谢同学从下往上走,一步可以走一级,也可以走两级。问他走到第n级楼梯,共有多少种走法?
Input
一行,一个正整数n, 1<=n<=40.
Output
一行,一个正整数,表示走到第n级有多少种走法。
9
-
Sample Input
55
-
Sample Output
Source/Category
典型的Fibonacci数
考虑使用矩阵快速幂解决。
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
struct matrix { // 定义一个矩阵
ll a[2][2];
matrix() { // 初始化
a[0][1] = a[1][0] = a[0][0] = a[1][1] = 0;
}
matrix operator* (matrix b) const { // 矩阵相乘
matrix res;
for (int i=0; i<2; ++i) {
for (int j=0; j<2; ++j) {
for (int k=0; k<2; ++k) {
res.a[i][j] += a[i][k]*b.a[k][j];
}
}
}
return res;
}
};
void quickpow(int b) { // 矩阵快速幂
matrix res, a;
res.a[0][0] = res.a[1][1] = 1; // 结果矩阵初始为单位矩阵
a.a[0][1] = a.a[1][0] = a.a[1][1] = 1; // 用矩阵[[0, 1], [1, 1]]求Fibonacci数
while (b) {
if (b&1) res = res*a;
a = a*a; b >>= 1;
}
printf("%lld", res.a[1][1]); // 最终结果的右下角数即为Fibonacci数
}
int main() {
int n; scanf("%d", &n);
quickpow(n);
return 0;
}