在 C++ 中找到給定 N 個三角形中的唯一三角形的數量


本題中,我們給出三個大小為 N 的陣列 s1[]、s2[] 和 s3[],表示 N 個三角形。我們的任務是找到給定的 N 個三角形中的唯一三角形的數量。

一個三角形要唯一,它的所有邊都應該是唯一的,即沒有其他三角形具有相同的邊。

我們舉個例子來理解一下這個問題,

輸入

s1[] = {1, 5, 3}
s2[] = {2, 3, 2}
s3[] = {4, 2, 5}

輸出

1

說明

邊長為 1 2 4 的三角形是唯一的。

解決方案方法

一個簡單的解決方案是計算唯一三角形的數量。

為此,我們首先對每個三角形的邊進行排序,然後儲存到對映中,如果它的值是唯一的,則增加計數。

說明我們解決方案工作原理的程式,

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int countUniqueTriangle(int a[], int b[], int c[], int n) {
   vector<int> triSides[n];
   map<vector<int>, int> m;
   for (int i = 0; i < n; i++) {
      triSides[i].push_back(a[i]);
      triSides[i].push_back(b[i]);
      triSides[i].push_back(c[i]);
      sort(triSides[i].begin(), triSides[i].end());
      m[triSides[i]] = m[triSides[i]] + 1;
   }
   map<vector<int>, int>::iterator itr;
   int uniqueTriCount = 0;
   for (itr = m.begin(); itr != m.end(); itr++) {
      if (itr->second == 1)
         if (itr->second == 1)
            uniqueTriCount++;
   }
   return uniqueTriCount;
}
int main() {
   int s1[] = { 1, 5 ,3 };
   int s2[] = { 2, 3, 2 };
   int s3[] = { 4, 2, 5 };
   int N = sizeof(s1) / sizeof(s1);
   cout<<"The number of unique triangles is "<<countUniqueTriangle(s1, s2, s3, N);
   return 0;
}

輸出

The number of unique triangles is 1

更新於: 15-Mar-2021

242 瀏覽

開啟你的 職業生涯

透過完成課程來獲取認證

立即開始
廣告
© . All rights reserved.