给定三个整数A , B和K。最初,第一个人比第二个人领先K kms。在每个小时中,第一个人向前行驶A公里,第二个人向前行驶B公里。任务是打印第二个人越过第一个人的小时数。如果无法这样做,请打印-1 。
例子:
Input: A = 4, B = 5, K = 1
Output: 2
Initially, the first person was ahead by 1 km.
After 1st hour the first and second person are at the same place.
After 2nd hour the first person moves ahead of the first person by 1 km.
Input: A = 6, B = 5, K = 1
Output: -1
天真的方法是线性检查每个小时,并在第二个人向前移动第一个人时打印第n个小时。
一种有效的方法是用数学方法解决问题。当第二个人领先于第一个人时,小时数将为K /(B – A)+ 1 。由于您需要覆盖K公里,因此花费的时间为K /(B – A) ,其中B – A是第二个人相对于第一个人的速度。如果A≥B,那么第二个人就不可能越过第一个人。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to return the number of
// hours for the second person to move ahead
int findHours(int a, int b, int k)
{
if (a >= b)
return -1;
// Time taken to equalize
int time = k / (b - a);
// Time taken to move ahead
time = time + 1;
return time;
}
// Driver code
int main()
{
int a = 4, b = 5, k = 1;
cout << findHours(a, b, k);
return 0;
}
Java
// Java implementation of the above approach
import java.io.*;
class GFG
{
// Function to return the number of
// hours for the second person to move ahead
static int findHours(int a, int b, int k)
{
if (a >= b)
return -1;
// Time taken to equalize
int time = k / (b - a);
// Time taken to move ahead
time = time + 1;
return time;
}
// Driver code
public static void main (String[] args)
{
int a = 4, b = 5, k = 1;
System.out.println (findHours(a, b, k));
}
}
// The code is contributed by ajit..@23
Python3
# Python3 implementation of the above approach
# Function to return the number of
# hours for the second person to move ahead
def findHours(a, b, k):
if (a >= b):
return -1
# Time taken to equalize
time = k // (b - a)
# Time taken to move ahead
time = time + 1
return time
# Driver code
a = 4
b = 5
k = 1
print(findHours(a, b, k))
# This code is contributed by mohit kumar 29
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to return the number of
// hours for the second person to move ahead
static int findHours(int a, int b, int k)
{
if (a >= b)
return -1;
// Time taken to equalize
int time = k / (b - a);
// Time taken to move ahead
time = time + 1;
return time;
}
// Driver code
static public void Main ()
{
int a = 4, b = 5, k = 1;
Console.Write(findHours(a, b, k));
}
}
// The code is contributed by ajit.
Javascript
输出:
2