一、明确需求
- 输入井的深度n、蠕虫每分钟上爬距离u、休息时下滑距离d。
- 若蠕虫能爬出井,输出所需时间(分钟);若不能,输出 "The worm cannot climb out of the well."。
- 蠕虫只要在某次上爬过程中头部到达井口(高度\(\geq n\)),就完成任务。
二、设计思路
- 特殊情况判断:若\(u \leq d\),蠕虫上爬后下滑,高度无法持续增加,必然爬不出,直接输出对应提示。
- 模拟爬动过程:当\(u > d\)时,模拟蠕虫 "上爬一分钟 + 休息下滑一分钟" 的循环,直到爬出井口。需记录当前高度与时间,每次上爬后检查是否爬出。
三、代码实现步骤(C++)
步骤 1:引入头文件与命名空间
使用#include<bits/stdc++.h>
包含常用标准库,using namespace std;
简化输入输出操作(无需每次写std::
)。
cpp
运行
#include<bits/stdc++.h>
using namespace std;
步骤 2:编写主函数main
程序从main
函数开始执行,所有逻辑在此实现。
cpp
运行
int main() {
// 后续代码写在这里
return 0; // 程序正常结束
}
步骤 3:输入数据
读取井深n、上爬距离u、下滑距离d。
cpp
运行
int n, u, d;
cin >> n >> u >> d;
步骤 4:处理爬不出的情况
若\(u \leq d\),直接输出提示并结束程序。
cpp
运行
if (u <= d) {
cout << "The worm cannot climb out of the well." << endl;
return 0;
}
步骤 5:模拟爬动过程
定义变量j
记录当前高度,te
记录时间,循环模拟 "上爬 + 检查 + 下滑" 过程。
cpp
运行
int j = 0, te = 0;
while (true) {
// 上爬一分钟
j += u;
te++;
// 检查是否爬出
if (j >= n) {
cout << te;
return 0;
}
// 休息下滑一分钟
j -= d;
te++;
}
四、完整代码
cpp
运行
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, u, d;
cin >> n >> u >> d;
if (u <= d) {
cout << "The worm cannot climb out of the well." << endl;
return 0;
}
int j = 0, te = 0;
while (true) {
j += u;
te++;
if (j >= n) {
cout << te;
return 0;
}
j -= d;
te++;
}
return 0;
}
五、测试示例
测试 1:能爬出
输入:
plaintext
10 2 1
模拟过程(关键步骤):
- 多次 "上爬2→下滑1" 后,第17分钟上爬时,高度达到10,输出
17
,与样例一致。
测试 2:爬不出
输入:
plaintext
20 1 3
因\(u=1 \leq d=3\),直接输出 "The worm cannot climb out of the well.",与样例一致。
大家还可以在我的bilibili(编程题小白日记)搜索 ···0052.爬动的蠕虫··· 找到这道题的视频解析