C. Ilya and Sticks解题报告
题目分类:贪心策略
题目描述:给n (1 ≤ n ≤ 105) 根筷子,梅根筷子都有一个长度li (2 ≤ li ≤ 106),求使用其中四根筷子首尾相接能组成的面积最大的矩形的面积是多少。每一根筷子最多可以被减低一个单位的长度。
解题思路:矩形一定有两组相等的对边。面积最大即四边长尽可能得大,将筷子从大到小排序,只要找到两组相等的边就行。注意考虑筷子可以降低长度。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
usingnamespace std;
constint N= 100010;
longlong a[N];
intmain()
{
int n;
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
scanf("%I64d",&a[i]);
sort(a,a+n);
longlong ans = 0;
int y=-1;
for(int i=n-2;i>=0;i--)
{
if(a[i+1]-a[i]<=1)
{
if(y==-1) y= i;
else
{
if(y!=i+1)
{
ans+= a[i]*a[y];
y=-1;
i--;
}
}
}
}
printf("%I64d\n",ans);
}
return0;
}
原题描述:
C.Ilya and Sticks
timelimit per test
2seconds
memorylimit per test
256megabytes
input
standardinput
output
standardoutput
In the evening, after the contest Ilya wasbored, and he really felt like maximizing. He remembered that he had a set ofn sticks and an instrument. Each stick is characterized by its length li.
Ilya decided to make a rectangle from thesticks. And due to his whim, he decided to make rectangles in such a way thatmaximizes 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 notallowed.
Sticks with lengthsa1,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 withlengths of, for example,3 3 3 3 or2 2 4 4. A rectangle cannot be made of, for example, sticks5 5 5 7.
Ilya also has an instrument which canreduce the length of the sticks. The sticks are made of a special material, sothe length of each stick can be reduced by at most one. For example, a stickwith length 5 can either stay at this length or betransformed into a stick of length4.
You have to answer the question — whatmaximum total area of the rectangles can Ilya get with a file if makesrectangles from the available sticks?
Input
The first line of the input contains apositive integern (1 ≤ n ≤ 105) — the number of the availablesticks.
The second line of the input containsn positive integersli (2 ≤ li ≤ 106) — the lengths of the sticks.
Output
Thefirst line of the output must contain a single non-negativeinteger — the maximum total area of the rectangles that Ilya can makefrom the available sticks.
Sampletest(s)
Input
4
2 4 4 2Output
8
Input
4
2 2 3 5Output
0
Input
4
100003 100004 100005 100006Output
10000800015