Algorithm
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 OX or OY 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.
The first line contains an integer n (1≤n≤100000) — the number of sticks Alexey got as a present.
The second line contains n integers a1,…,an (1≤ai≤10000) — the lengths of the sticks.
Print one integer — the square of the largest possible distance from (0,0) to the tree end.
3 1 2 3
26
4 1 1 2 2
20
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.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define debug(n) cout<<(n)<<endl;
const ll INF = 2e18 + 99;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
deque <ll> deck;
ll x;
for(int i = 0; i < n; i++){
cin>>x;
deck.push_back(x);
}
sort(deck.begin(), deck.end(), greater<int>());
ll hz = 0;
ll vt = 0;
bool check = false;
for(int i = 0; i < n; i++){
check = !check;
if(check){
hz += deck.front();
deck.pop_front();
}
else{
vt += deck.back();
deck.pop_back();
}
}
ll dist = hz * hz + vt * vt;
cout<<dist<<endl;
}
Copy The Code &
Try With Live Editor
Input
1 2 3
Output
Demonstration
Codeforcee solution 1248-B B. Grow The Tree C++, Java, Js and Python,1248-B,codeforcee solution