B. Grow The Tree Codeforces Round #594 (Div. 2)

Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher’s Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.

The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point (0,0)
. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to ??or ?? axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.

Alexey wants to make a polyline in such a way that its end is as far as possible from (0,0). Please help him to grow the tree this way.

Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

Input
The first line contains an integer ?
n
(1≤?≤100000) — the number of sticks Alexey got as a present.

The second line contains ?
n
integers ?1,…,??
(1≤??≤10000) — the lengths of the sticks.

Output
Print one integer — the square of the largest possible distance from (0,0)
to the tree end.
Examples
inputCopy
3
1 2 3
outputCopy
26
inputCopy
4
1 1 2 2
outputCopy
20
Note
The following pictures show optimal trees for example tests. The squared distance in the first example equals 5⋅5+1⋅1=26 .
And in the second example 4⋅4+2⋅2=20

解题思路:为了达到题目要求的离远点最远,长要尽可能地长,宽要尽可能地短,将棍棒长度进行排序,对半分,长度为后一半棍棒长度和,宽度为前一半棍棒的长度和。棍棒顺序为一横一竖,不允许多个横着或多个竖着。

AC代码:

#include <iostream>
#include <algorithm>
using namespace std;
long long a[100005];
int main()
{
    long long n,lenx=0,leny=0;
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    sort(a,a+n+1);
        for(int i=1;i<=n;i++)
        {
            if(i<=n/2)
                lenx+=a[i];
            else
                leny+=a[i];
        }    
        
    cout<<lenx*lenx+leny*leny<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lovelcy/p/11824541.html