给定一个由N 个正整数和两个整数X和Y组成的数组 arr[] ,任务是检查是否有可能从(0, 0)到达 (X, Y)使得移动到(X f , Y f ) from (X i , Y i )仅当它们之间的欧几里得距离存在于数组arr[] 中时才被允许。如果可能,则打印Yes 。否则,打印No 。
注意:数组 arr[] 中存在的每个距离最多可以使用一次。
例子:
Input: arr[ ] = {2, 5}, X = 5, Y= 4
Output: Yes
Explanation:
Following are the moves required to reach from (0, 0) to (5, 4):
- Move from point (0, 0) to (2, 0). The euclidian distance is sqrt((2 – 0)2 + (0 – 0)) = 2, which is present in the array.
- Move from point (2, 0) to (5, 4). The euclidian distance is sqrt((5 – 2)2 + (4 – 0)2) = 5, which is present in the array.
After the above set of moves, the point (5, 4) can be reached. Hence, print Yes.
Input: arr[] = {4}, X = 3, Y= 4
Output: No
方法:通过将点(0, 0)到(X, Y)之间的欧几里德距离视为Z = sqrt(X*X + Y*Y) ,可以通过使用以下观察来解决给定的问题,那么问题可以是分为3种情况:
- 如果数组元素的总和小于Z ,则任何一组移动都不可能到达(X, Y)。
- 如果数组元素的总和等于Z ,则有可能在N 次移动后到达 (X, Y)。
- 否则对于每个距离检查以下条件:
- 如果对于任何A[i] , A[i] > Z + (除 A[i] 之外的所有其他距离)那么永远不可能到达(X, Y)因为路径将是一个多边形并且对于一个 N 多边形对于每个可能的边,(N – 1) 边的总和必须大于另一边。
- 否则,总是有可能到达(X, Y) 点。
根据上述三种情况的观察,相应地打印结果。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if the point (X, Y)
// is reachable from (0, 0) or not
int isPossibleToReach(int A[], int N, int X, int Y)
{
// Find the Euclidian Distance
double distance = sqrt(double(X * X + Y * Y));
// Calculate the maximum distance
double mx = 0;
for (int i = 0; i < N; i++) {
mx += double(A[i]);
}
// Case 1.
if (mx < distance) {
cout << "NO";
return 0;
}
// Case 2.
if ((mx - distance) < 0.000001) {
cout << "YES";
return 0;
}
// Otherwise, check for the polygon
// condition for each side
for (int i = 0; i < N; i++) {
if (distance + mx
< double(2) * double(A[i])) {
cout << "No";
return 0;
}
}
// Otherwise, print Yes
cout << "Yes";
return 0;
}
// Driver Code
int main()
{
int A[] = { 2, 5 };
int X = 5, Y = 4;
int N = sizeof(A) / sizeof(A[0]);
isPossibleToReach(A, N, X, Y);
return 0;
}
Python3
# Python program for the above approach
import math
# Function to check if the po(X, Y)
# is reachable from (0, 0) or not
def isPossibleToReach(A, N, X, Y):
# Find the Euclidian Distance
distance = math.sqrt(X * X + Y * Y)
# Calculate the maximum distance
mx = 0
for i in range(N):
mx += A[i]
# Case 1.
if (mx < distance):
print("NO")
return 0
# Case 2.
if ((mx - distance) < 0.000001):
print("YES")
return 0
# Otherwise, check for the polygon
# condition for each side
for i in range(N):
if (distance + mx < (2) * (A[i])):
print("No")
return 0
# Otherwise, prYes
print("Yes")
return 0
# Driver Code
A = [2, 5]
X = 5
Y = 4
N = len(A)
isPossibleToReach(A, N, X, Y)
# This code is contributed by shivani.
输出:
Yes
时间复杂度: O(N)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。