给定一个三角形ABC 。绘制从AB侧到AC侧的H条水平线(如图)和从顶点A到BC侧的V条垂直线,任务是找到总数。形成的三角形。
例子:
Input: H = 2, V = 2
Output: 18
As we see in the image above, total triangles formed are 18.
Input: H = 3, V = 4
Output: 60
方法:如下图所示,我们可以推导出上述问题的一般公式:
- 如果只有h 条水平线,则总三角形为(h + 1) 。
- 如果只有v 条垂直线,则三角形总数为(v + 1) * (v + 2) / 2。 .
- 因此,总三角形是由水平线形成的三角形* 由垂直线形成的三角形,即(h + 1) * (( v + 1) * (v + 2) / 2) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define LLI long long int
// Function to return total triangles
LLI totalTriangles(LLI h, LLI v)
{
// Only possible triangle is
// the given triangle
if (h == 0 && v == 0)
return 1;
// If only vertical lines are present
if (h == 0)
return ((v + 1) * (v + 2) / 2);
// If only horizontal lines are present
if (v == 0)
return (h + 1);
// Return total triangles
LLI Total = (h + 1) * ((v + 1) * (v + 2) / 2);
return Total;
}
// Driver code
int main()
{
int h = 2, v = 2;
cout << totalTriangles(h, v);
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to return total triangles
public static int totalTriangles(int h, int v)
{
// Only possible triangle is
// the given triangle
if (h == 0 && v == 0)
return 1;
// If only vertical lines are present
if (h == 0)
return ((v + 1) * (v + 2) / 2);
// If only horizontal lines are present
if (v == 0)
return (h + 1);
// Return total triangles
int total = (h + 1) * ((v + 1) * (v + 2) / 2);
return total;
}
// Driver code
public static void main(String[] args)
{
int h = 2, v = 2;
System.out.print(totalTriangles(h, v));
}
}
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return total triangles
public static int totalTriangles(int h, int v)
{
// Only possible triangle is
// the given triangle
if (h == 0 && v == 0)
return 1;
// If only vertical lines are present
if (h == 0)
return ((v + 1) * (v + 2) / 2);
// If only horizontal lines are present
if (v == 0)
return (h + 1);
// Return total triangles
int total = (h + 1) * ((v + 1) * (v + 2) / 2);
return total;
}
// Driver code
public static void Main()
{
int h = 2, v = 2;
Console.Write(totalTriangles(h, v));
}
}
// This code is contributed by Ryuga
Python3
# Python3 implementation of the approach
# Function to return total triangles
def totalTriangles(h, v):
# Only possible triangle is
# the given triangle
if (h == 0 and v == 0):
return 1
# If only vertical lines are present
if (h == 0):
return ((v + 1) * (v + 2) / 2)
# If only horizontal lines are present
if (v == 0):
return (h + 1)
# Return total triangles
total = (h + 1) * ((v + 1) * (v + 2) / 2)
return total
# Driver code
h = 2
v = 2
print(int(totalTriangles(h, v)))
PHP
Javascript
输出:
18
时间复杂度: O(1)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。