给定三个正整数a,b和d 。您当前位于无限2D坐标平面上的原点(0,0)。您可以从当前位置以等于或等于a或b的欧几里得距离跳到2D平面上的任何点。任务是找到从(0,0)达到(d,0)所需的最小跳数。
例子:
Input : a = 2, b = 3, d = 1
Output : 2
First jump of length a = 2, (0, 0) -> (1/2, √15/2)
Second jump of length a = 2, (1/2, √15/2) -> (1, 0)
Thus, only two jump are required to reach
(1, 0) from (0, 0).
Input : a = 3, b = 4, d = 11
Output : 3
(0, 0) -> (4, 0) using length b = 4
(4, 0) -> (8, 0) using length b = 4
(8, 0) -> (11, 0) using length a = 3
#include
using namespace std;
// Return the minimum jump of length either a or b
// required to reach (d, 0) from (0, 0).
int minJumps(int a, int b, int d)
{
// Assigning maximum of a and b to b
// and assigning minimum of a and b to a.
int temp = a;
a = min(a, b);
b = max(temp, b);
// if d is greater than or equal to b.
if (d >= b)
return (d + b - 1) / b;
// if d is 0
if (d == 0)
return 0;
// if d is equal to a.
if (d == a)
return 1;
// else make triangle, and only 2
// steps required.
return 2;
}
int main()
{
int a = 3, b = 4, d = 11;
cout << minJumps(a, b, d) << endl;
return 0;
}
输出:
3
有关更多详细信息,请参阅完整文章:给定长度以达到从2D平面原点到形式(d,0)的点所需的跳数。
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。