让他爬到满足他的条件的楼梯顶端的最小步数是多少?
单行包含两个空格分隔的整数n,m(0 打印单个整数 - 最小步长为m的倍数。如果他无法攀登令人满意的条件打印 - 1而不是。 对于第一个样本,John可以按照以下步骤顺序攀爬6次:{2,2,2,2,1,1}。 对于第二个样本,只有三个有效的步骤序列{2,1},{1,2},{1,1,1}分别具有2,2和3个步骤。所有这些数字都不是5的倍数。 我一直在努力解决这个问题,所以我想使用比给定数字少2但最接近错误答案的最近功率输出
样品测试
Input
10 2
Output
6
Input
3 5
Output
-1
注意:
我的代码:
#include<stdio.h>
#include<math.h>
using namespace std;
int main(){
int n,m;
scanf("%d %d",&n,&m);
int x= pow (2,floor (log2(n)) );
int rem = n-x;
int ans = ((x/2)+rem);
if ( ans % m == 0 )
printf (" %d \n ",ans);
else
printf("-1\n");
return 0;
}
答案 0 :(得分:1)
我个人并不知道两人的力量是如何有用的。
让我们先在伪代码中编写不同的算法:
N = number of steps
M = desired multiple
# Excluding any idea of the multiple restraint, what is the maximum and minimum
# number of steps that John could take?
If number of steps is even:
minimum = N / 2
maximum = N
If number of steps is odd:
minimum = N / 2 + 1
maximum = N
# Maybe the minimum number of steps is perfect?
If minimum is a multiple of M:
Print minimum
# If it isn't, then we need to increase the number of steps up to a multiple of M.
# We then need to make sure that it didn't surpass the maximum number of steps.
Otherwise:
goal = minimum - (minimum % M) + M
if goal <= maximum:
Print goal
Otherwise:
Print -1
然后我们可以将其转换为代码:
#include <cstdio>
int main(){
int n,m;
scanf("%d %d", &n, &m);
const int minimum = (n / 2) + (n % 2);
const int maximum = n;
if (minimum % m == 0) {
printf("%d\n", minimum);
return 0;
}
const int guess = minimum - (minimum % m) + m;
if (guess <= maximum) {
printf("%d\n", guess);
return 0;
}
printf("%d\n", -1);
return 0;
}
我在这里使用的关键工具是,我知道约翰可以在(和包括)[minimum, maximum]
之间的任何步骤组合中缩放楼梯。我们怎样才能确定这个?