跳到正文

题解

M³OJ | dp专练01 | T1 | 签到题~ | 题解

JHR100330约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月15日
篇幅
约 2 分钟

版本

  1. v1当前

#1 深搜(20pts20pts)

#2 dp(未优化,80pts80pts):

每次可以向下一次跨一到两阶,有点像经典的斐波那契数列。

令 dp[i]dp[i] 为向下走 ii 阶的总方案数,转移方程:

dp[i]=dp[i−1]+dp[i−2]dp[i] = dp[i - 1] + dp[i - 2]

初始化:dp[0]=1dp[0] = 1。

但有一点不一样,就是可以从任意位置直接跳到最下方。

所以答案应该为到达每一阶的方案数之和,即为:

∑i=0ndp[i]\displaystyle{\sum^{n}_{i = 0}dp[i]}

最后记得加上取模即可。

80pts80pts Code:

C++
#include<bits/stdc++.h>

using namespace std;

#define endl '\n'

const int mod = 1e9 + 7;
int n;
int dp[10000050], ans = 2;

signed main(){
	scanf("%d", &n);
	dp[0] = dp[1] = 1;
	for(int i = 2; i <= n; i ++){
		dp[i] = (dp[i - 1] + dp[i - 2]) % mod;
		ans = (ans + dp[i]) % mod;
	}
	printf("%d\n", ans);
	return 0;
}

#3 dp(优化空间,100pts100pts):

注意到,每次 dpdp 数组的转移仅与前两位有关联,那么就可以将数组优化成变量。

在这里就不过多解释了。

AC Code:

C++
#include<bits/stdc++.h>

using namespace std;

#define endl '\n'

const int mod = 1e9 + 7;
int n;
int a = 1, b = 1, c, ans = 1;

signed main(){
	scanf("%d", &n);
	for(int i = 1; i <= n; i ++){
		ans = (ans + b) % mod;
		c = (a + b) % mod;
		a = b;
		b = c;
	}
	printf("%d\n", ans);
	return 0;
}
原文