英文原题
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li.
Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.
Sticks with lengths a1, a2, a3 and a4 can make a rectangle if the following properties are observed:
- a1 ≤ a2 ≤ a3 ≤ a4
- a1 = a2
- a3 = a4
A rectangle can be made of sticks with lengths of, for example, 3 3 3 3 or 2 2 4 4. A rectangle cannot be made of, for example, sticks 5 5 5 7.
Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4.
You have to answer the question — what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?
Input
The first line of the input contains a positive integer n (1 ≤ n ≤ 105) — the number of the available sticks.
The second line of the input contains n positive integers li (2 ≤ li ≤ 106) — the lengths of the sticks.
Output
The first line of the output must contain a single non-negative integer — the maximum total area of the rectangles that Ilya can make from the available sticks.
题目意思是给你一堆长度不一的棒子,利用他们本来的长度或者原来长度减一来拼一些长方形,求最后能拼出的矩形最大总面积。样例如下:
Input
4
2 4 4 2
Output
8
Input
4
2 2 3 5
Output
0
Input
4
100003 100004 100005 100006
Output
10000800015
这题想到的是用贪心,先把棒子按长度由小到大排序,然后从大到小判断能否配对,遇到长度一样的两根就放入Pair数组,否则跳过。在从Pair数组里从大到小去矩形边(当然最终是偶数项)做面积加和。
代码:
#include <iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int n;//棍数
long long int len[200005];//棒子数组
long long int pairs[200005];//配上对的棒子
long long int S;//最后总面积
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%I64d",&len[i]);
}
sort(len,len+n);//排序
int p=0;
for(int i=n-1;i>=0;i--)
{
if(i>0&&(len[i]==len[i-1]))
{
pairs[p]=len[i];
p++;
i--;
}else if(i>0&&(len[i]-1==len[i-1]))
{
pairs[p]=len[i]-1;
p++;
i--;
}
}
S=0;
for(int i=0;2*i<=p;i++)
{
S+=pairs[2*i]*pairs[2*i+1];
}
printf("%I64d\n",S);
return 0;
}