📜  使用运算符重载来计算唯一三角形的数量

📅  最后修改于: 2021-04-27 19:10:18             🧑  作者: Mango

给定N个三角形及其三个边的长度,分别为a,b和c 。任务是计算这N个给定三角形中唯一三角形的数量。如果两个三角形中至少有一个不同的边,则它们互不相同。

例子:

使用上一篇文章中的STL排序集可以解决此问题。

方法:我们将在基于类的关系运算符(==)重载的情况下,讨论基于运算符重载的方法来解决此问题。

  • 由于如果一组中的每个元素对应于另一组中的元素,则说{2,5,6},{6,5,4}的三角形的任意两组边都相等。因此,我们将检查一个集合中的每个元素与另一个集合中的元素,并对其进行计数。如果计数相同,则可以简单地将这两个集合视为相等。现在,我们使用关系运算符简单地比较了集合,以找到唯一的集合数。
  • 为了获得唯一集合的数量,我们可以采用一种将当前集合的唯一性与前面的集合进行比较的方法。因此,如果将有k个相同类型的集合,则仅最后一个集合将被视为唯一。

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

C++
// C++ program for the above approach
#include 
using namespace std;
  
// Structure to represent a Triangle
// with three sides as a, b, c
struct Triangle {
    int a, b, c;
  
public:
    bool operator==(const Triangle& t) const;
};
  
// Function to overload relational
// operator (==)
bool Triangle::operator==(const Triangle& t) const
{
    int cnt = 0;
    if ((this->a == t.a)
        || (this->a == t.b)
        || (this->a == t.c)) {
        cnt++;
    }
    if ((this->b == t.a)
        || (this->b == t.b)
        || (this->b == t.c)) {
        cnt++;
    }
    if ((this->c == t.a)
        || (this->c == t.b)
        || (this->c == t.c)) {
        cnt++;
    }
  
    // If all the three elements a, b, c
    // are same, triangle is not unique
    if (cnt == 3) {
        return false;
    }
  
    // For unique triangle return true
    return true;
}
  
// Function returns the number
// of unique Triangles
int countUniqueTriangles(struct Triangle arr[],
                         int n)
{
  
    // Unique sets
    int uni = 0;
  
    for (int i = 0; i < n - 1; i++) {
  
        // Check on uniqueness for a
        // particular set w.r.t others
        int cnt = 0;
  
        for (int j = i; j < n - 1; j++) {
  
            // Checks if two triangles
            // are different
            if (arr[i] == arr[j + 1])
                cnt++;
        }
  
        // If count of unique triangles
        // is same as the number of remaining
        // triangles then, increment count
        if (cnt == n - 1 - i)
            uni++;
    }
  
    // Since last element that
    // remains will be unique only
    return uni + 1;
}
  
// Driver Code
int main()
{
    // An array of structure to
    // store sides of Triangles
    struct Triangle arr[] = {
        { 3, 2, 2 }, { 3, 4, 5 }, { 1, 2, 2 },
        { 2, 2, 3 }, { 5, 4, 3 }, { 6, 4, 5 }
    };
  
    int n = sizeof(arr) / sizeof(Triangle);
  
    // Function Call
    cout << countUniqueTriangles(arr, n);
    return 0;
}


输出:
4

时间复杂度: O(N)
辅助空间: O(1)