给定两个整数X和Y ,任务是找到X圆和Y直线之间可能的最大交点数。
例子:
Input: X = 4, Y = 4
Output: 50
Explanation:
4 lines intersect each other at 6 points and 4 circles intersect each other at maximum of 12 points.
Each line intersects 4 circles at 8 points.
Hence, 4 lines intersect four circles at a maximum of 32 points.
Thus, required number of intersections = 6 + 12 + 32 = 50.
Input: X = 3, Y = 4
Output: 36
方法:
可以观察到,存在三种类型的交叉点:
- 从 X 个圆中选择一对点的方法数是 .每个这样的对最多相交两点。
- 从 Y 线上选择一对点的方法数是 .每对这样的对至多在一点相交。
- 从 X 圆和 Y 线中选择一个圆和一条线的方法数是 .每个这样的对最多在两个点上相交。
So, the maximum number of point of intersection can be calculated as:
=>
=>
因此,求X圆与Y直线的最大交点数的公式为:
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
int maxPointOfIntersection(int x, int y)
{
int k = y * (y - 1) / 2;
k = k + x * (2 * y + x - 1);
return k;
}
// Driver code
int main()
{
// Number of circles
int x = 3;
// Number of straight lines
int y = 4;
// Function Call
cout << (maxPointOfIntersection(x, y));
}
// This code is contributed by Ritik Bansal
Java
// Java program to implement
// the above approach
class GFG{
static int maxPointOfIntersection(int x, int y)
{
int k = y * (y - 1) / 2;
k = k + x * (2 * y + x - 1);
return k;
}
// Driver code
public static void main(String[] args)
{
// Number of circles
int x = 3;
// Number of straight lines
int y = 4;
// Function Call
System.out.print(maxPointOfIntersection(x, y));
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program to implement
# the above approach
def maxPointOfIntersection(x, y):
k = y * ( y - 1 ) // 2
k = k + x * ( 2 * y + x - 1 )
return k
# Number of circles
x = 3
# Number of straight lines
y = 4
# Function Call
print(maxPointOfIntersection(x, y))
C#
// C# program to implement
// the above approach
using System;
class GFG{
static int maxPointOfIntersection(int x, int y)
{
int k = y * (y - 1) / 2;
k = k + x * (2 * y + x - 1);
return k;
}
// Driver code
public static void Main(String[] args)
{
// Number of circles
int x = 3;
// Number of straight lines
int y = 4;
// Function Call
Console.Write(maxPointOfIntersection(x, y));
}
}
// This code is contributed by Princi Singh
Javascript
输出:
36
时间复杂度: O(1)
辅助空间: O(1)