📌  相关文章
📜  使用STL计算唯一三角形的数量|设置1(使用设置)

📅  最后修改于: 2021-05-25 21:04:17             🧑  作者: Mango

我们给了n个三角形以及三个边的长度,分别为a,b,c。现在我们需要计算这n个给定三角形中唯一三角形的数量。如果两个三角形中至少有一个不同的边,则它们互不相同。

例子:

Input: arr[] = {{1, 2, 2},
                {4, 5, 6}, 
                {4, 5, 6}    
Output: 2

Input: arr[] = {{4, 5, 6}, {6, 5, 4},
                {1, 2, 2}, {8, 9, 12}
Output: 3

强烈建议您最小化浏览器,然后自己尝试。

由于要求我们查找“唯一”三角形的数量,因此我们可以使用set或unordered_set。在本文中,将讨论基于集合的方法。

如何将三个面作为元素存储在容器中?我们使用STL对将所有三个面存储在一起

pair  >

我们一个接一个地将所有三角形插入集合中。但是这种方法的问题在于,边为{4,5,6}的三角形与边为{5,4,6}的三角形虽然指的是相同的三角形,却与边三角形不同。

为了处理这种情况,我们将边按排序顺序存储(基于边的长度),这里的排序不会成为问题,因为我们只有3个边,并且可以在恒定时间内对其进行排序。例如,将{5,4,6}插入到集{4,5,6}中

注意:我们可以通过make_pair(a,b)进行配对,也可以简单地使用{a,b}。

以下是上述想法的C++实现:

// A C++ program to find number of unique Triangles
#include 
using namespace std;
  
// Creating shortcut for an integer pair.
typedef pair iPair;
  
// A structure to represent a Triangle with
// three sides as a, b, c
struct Triangle
{
    int a, b, c;
};
  
// A function to sort three numbers a, b and c.
// This function makes 'a' smallest, 'b' middle
// and 'c' largest (Note that a, b and c are passed
// by reference)
int sort3(int &a, int &b, int &c)
{
    vector arr({a, b, c});
    sort(arr.begin(), arr.end());
    a = arr[0]; b = arr[1]; c = arr[2];
}
  
// Function returns the number of unique Triangles
int countUniqueTriangles(struct Triangle arr[],
                           int n)
{
    // A set which consists of unique Triangles
    set < pair< int, iPair > > s;
  
    // Insert all triangles one by one
    for (int i=0; i

输出:

Number of Unique Triangles are 4

上述解决方案的时间复杂度为O(n Log n),因为设置需要O(Log n)插入时间。

我们可以使用unordered_set将时间复杂度提高到O(n)。但是使用unordered_set要求编写一个哈希函数,因为在库中未对成对定义哈希函数。

相关文章:可能的三角形数

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”