问题 A: Make a Rectangle
时间限制: 1 Sec 内存限制: 128 MB
提交: 668 解决: 197
[提交] [状态] [讨论版] [命题人:admin]
题目描述
We have N sticks with negligible thickness. The length of the i-th stick is Ai.
Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides. Find the maximum possible area of the rectangle.
Constraints
4≤N≤105
1≤Ai≤109
Ai is an integer.
输入
Input is given from Standard Input in the following format:
N
A1 A2 ... AN
输出
Print the maximum possible area of the rectangle. If no rectangle can be formed, print 0.
样例输入
6 3 1 2 4 2 1
样例输出
2
提示
1×2 rectangle can be formed.
题目大意: 给你一串序列代表木棍的长度,从里面挑四个木棍组成矩形(包括正方形),输出可能组成最大矩形的面积。
思路:
既然要找面积最大的木棍,那我们就将木棍的长度降序排列,因为木棍长度范围是 1e9,本来想开哈希数组奈何太大了不太方便,我也不太会哈希....就用了时间复杂度比较高的map。在一遍for循环里,一边计数一边判断能否构成矩形。
- 正方形:需要四根相同长度的木棍。
- 长方形:需要四根两两长度相同的木棍。
*具体实现细节看代码。
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool cmp(ll a, ll b)
{
return a > b;
}
int main()
{
int n;
while(cin >> n)
{
ll b[n];
map<int,int>a;
for(int i=0; i<n; i++)
cin >> b[i];
sort(b,b+n,cmp);
ll x[3];
int cnt = 0;
int tmp = -1;
for(int i=0; i<n; i++)
{
a[b[i]] ++;
if(a[b[i]] == 2)
{
x[cnt++] = b[i];
tmp = b[i];
}
else if(a[b[i]] == 4 && b[i]==tmp)
{
x[cnt++] = b[i];
}
if(cnt == 2)
break;
}
if(cnt != 2)
{
cout << "0" << endl;
continue;
}
ll ans = x[0]*x[1];
cout << ans << endl;
}
return 0;
}
欢迎指正与交流。