ในปัญหานี้ เราได้รับสามอาร์เรย์ s1[] , s2[] และ s3[] ขนาด N ซึ่งแสดงถึงรูปสามเหลี่ยม 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