C - Ilya and Sticks
Posted acgoto
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C - Ilya and Sticks相关的知识,希望对你有一定的参考价值。
Problem description
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.
Examples
4
2 4 4 2
8
4
2 2 3 5
0
4
100003 100004 100005 100006
10000800015
解题思路:题目的意思就是将每个能组成长方形的面积累加求和,并且使得面积S总最大。怎么使得S最大呢?做法:将长度先排序,再从长度大的往长度小的贪心,因为每根棍可以选择减掉1或0的长度,所以相邻棍的长度只要相差值不大于1即可组成长方形的一组边,这样一直往前找配对矩形的一组边,将其相乘再累加求和最后就能得到最大的矩形面积。
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+5; 4 typedef long long LL; 5 int n,m=0,a[maxn];LL ans=0,mul=1; 6 int main(){ 7 cin>>n; 8 for(int i=0;i<n;++i)cin>>a[i]; 9 sort(a,a+n); 10 for(int i=n-1;i>0;--i){ 11 if(a[i]-a[i-1]<=1){mul*=a[i-1];i--;m++;} 12 if(m==2){ans+=mul;mul=1;m=0;} 13 } 14 cout<<ans<<endl; 15 return 0; 16 }
以上是关于C - Ilya and Sticks的主要内容,如果未能解决你的问题,请参考以下文章
C - Ilya And The Tree Codeforces Round #430 (Div. 2)
CF 842C Ilya And The Tree(树上DFS)
●CodeForces 518D Ilya and Escalator