在这个问题中,我们得到了由N个整数组成的数组,这些数组表示n条棍子的长度。我们的任务是打印可以从给定长度的棒中创建的矩形和正方形的计数。
让我们以一个例子来了解问题
输入 -数组= {5、5、7、7、1、4}
输出 -1
说明 -具有边5 5 7 7。
为了解决这个问题,我们将不得不检查矩形和正方形是否可行。
现在,要创建一个正方形或矩形,应该有两个长度相同的棒,矩形的2个,正方形的4个。现在,在我们的数组中,我们将必须检查相同长度的成对的棒。为了使搜索容易,我们将对数组进行排序,然后找到对,总对数的一半将是可以创建的正方形或矩形数。
显示我们解决方案实施情况的程序,
#include <bits/stdc++.h>
using namespace std;
int countRecSqr(int sticks[], int n) {
sort(sticks, sticks + n);
int pairs = 0;
for (int i = 0; i < n - 1; i++) {
if (sticks[i]==sticks[i + 1]) {
pairs++;
i++;
}
}
return pairs / 2;
}
int main() {
int sticks[] = { 2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 };
int n = sizeof(sticks) / sizeof(sticks[0]);
cout<<"The total number of squares or rectangles that can be created is ";
cout<<countRecSqr(sticks, n);
return 0;
}输出结果
The total number of squares or rectangles that can be created is 3