题目:
A. Dreamoon and Stairs
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated integers n, m (0 < n ≤ 10000, 1 < m ≤ 10).
Output
Print a single integer — the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print - 1 instead.
Examples
input
10 2
output
6
input
3 5
output
-1
Note
For the first sample, Dreamoon could climb in 6 moves with following sequence of steps: {2, 2, 2, 2, 1, 1}.
For the second sample, there are only three valid sequence of steps {2, 1}, {1, 2}, {1, 1, 1} with 2, 2, and 3 steps respectively. All these numbers are not multiples of 5.
题意:
要爬一个n阶的楼梯,每次只能爬一阶或两阶,题目要求最后爬的次数要是m的倍数,求所需要爬的最小的次数
思路:
我的直觉思路是写个递归,每次有两个选择,直到爬了n阶楼梯,记录一共需要多少步。这个思路第一次超时了,然后我改了一下思路,既然存在最小值,那么爬到某个高度所需的最小的步数一定是确定的,用一个vis数组来记录每个高度最小的步数,如果存在更少的步数就能到达这个高度则继续递归。当然还有其他的解法。
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, ans;
const int maxn = 10000+10;
int vis[maxn];
void dfs(int depth, int len){
if(len==n){
if(depth%m==0)
ans = min(ans, depth);
return;
}
if(len<n){
if(depth+1<vis[len+1]){
dfs(depth+1, len+1);
vis[len+1] = depth+1;
}
if(depth+1<vis[len+2]){
dfs(depth+1, len+2);
vis[len+2] = depth+1;
}
}
}
int main(){
while(cin>>n>>m){
ans = 0x7f7f7f7f;
memset(vis, 0x7f, sizeof(vis));
dfs(0, 0);
if(ans==0x7f7f7f7f) cout<<-1<<endl;
else cout<<ans<<endl;
}
return 0;
}
本文介绍了一种解决特定爬楼梯问题的方法,即找到达到楼梯顶部所需的、为给定整数倍数的最少步数。通过使用递归算法,并结合记忆化搜索技术优化,解决了在每一步可以选择爬1或2阶的情况下,使总步数为指定整数倍数的问题。
380

被折叠的 条评论
为什么被折叠?



