给定半径为r的圆并以point(x1,y1)为中心,并给出一个point(x2,y2)。任务是使用最少的步数将圆心从给定的中心(x1,y1)移至目标(x2,y2)。第一步,我们可以在任意点上将销钉放在圆的边界上,然后围绕该销钉旋转圆弧任意角度,最后取下销钉。
例子 :
Input : r = 2
x1 = 0, y1 = 0
x2 = 0, y2 = 4
Output :1
Input : r = 1
x1 = 1, y1 = 1,
x2 = 4, y2 = 4
Output : 3
让我们考虑两个中心之间的直线。显然,要使中心移动最大距离,我们需要将其绕直线旋转180度。因此,每次我们可以移动中心的最大距离为2 * r。让我们继续每次以2 * r的距离移动中心,直到两个圆相交。现在显然可以通过围绕两个圆的交点之一旋转中心,使其到达最终位置,从而使中心移至最终位置。
每次使圆移动2 * r次(最后一次移动除外),它都会小于<2 * r。设两点之间的初始距离为d。该问题的解决方案将是ceil(d / 2 * r)。
C++
// C++ program to find minimum number of
// revolutions to reach a target center
#include
using namespace std;
// Minimum revolutions to move center from
// (x1, y1) to (x2, y2)
int minRevolutions(double r, int x1, int y1,
int x2, int y2)
{
double d = sqrt((x1 - x2)*(x1 - x2) +
(y1 - y2)*(y1 - y2));
return ceil(d/(2*r));
}
// Driver code
int main()
{
int r = 2, x1 = 0, y1 = 0, x2 = 0, y2 = 4;
cout << minRevolutions(r, x1, y1, x2, y2);
return 0;
}
Java
// Java program to find minimum number of
// revolutions to reach a target center
class GFG {
// Minimum revolutions to move center
// from (x1, y1) to (x2, y2)
static double minRevolutions(double r,
int x1, int y1, int x2, int y2)
{
double d = Math.sqrt((x1 - x2)
* (x1 - x2) + (y1 - y2)
* (y1 - y2));
return Math.ceil(d / (2 * r));
}
// Driver Program to test above function
public static void main(String arg[]) {
int r = 2, x1 = 0, y1 = 0;
int x2 = 0, y2 = 4;
System.out.print((int)minRevolutions(r,
x1, y1, x2, y2));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to find
# minimum number of
# revolutions to reach
# a target center
import math
# Minimum revolutions to move center from
# (x1, y1) to (x2, y2)
def minRevolutions(r,x1,y1,x2,y2):
d = math.sqrt((x1 -x2)*(x1 - x2) +
(y1 - y2)*(y1 - y2))
return math.ceil(d//(2*r))
# Driver code
r = 2
x1 = 0
y1 = 0
x2 = 0
y2 = 4
print(minRevolutions(r, x1, y1, x2, y2))
# This code is contributed
# by Anant Agarwal.
C#
// C# program to find minimum number of
// revolutions to reach a target center
using System;
class GFG {
// Minimum revolutions to move center
// from (x1, y1) to (x2, y2)
static double minRevolutions(double r,
int x1, int y1, int x2, int y2)
{
double d = Math.Sqrt((x1 - x2)
* (x1 - x2) + (y1 - y2)
* (y1 - y2));
return Math.Ceiling(d / (2 * r));
}
// Driver Program to test above function
public static void Main()
{
int r = 2, x1 = 0, y1 = 0;
int x2 = 0, y2 = 4;
Console.Write((int)minRevolutions(r,
x1, y1, x2, y2));
}
}
// This code is contributed by nitin mittal.
PHP
输出 :
1
时间复杂度: O(1)