We have n piles of apples, and we want to move the piles into a single large pile using the least possible amount of energy. Only two piles can be combined at a time and two piles with a and b apples can be combined together with the cost of (a+b) energy units.
We want to know the minimum amount of energy required to combine all piles of apples together.
Input:
apple(n, lst)
where lst contains n numbers representing the number of apples in each pile.
#include<algorithm> using namespace std; int apple(int n, int* a) { if (n < 2) return 0; int* end = a+n; int sum = 0; while (end > a+1) { std::make_heap(a, end, greater<int>()); std::pop_heap(a, end, greater<int>()); --end; sum += (*a += *end); } return sum; }
#include<stdio.h>#include<queue>- #include<algorithm>
- using namespace std;
int apple(int n,int* a)- int apple(int n, int* a)
- {
priority_queue<int,vector<int>,greater<int> >q;for(int i=0; i<n; i++)q.push(a[i]);int ans=0,tmp;while(q.size()>=2){tmp=0;tmp+=q.top();q.pop();tmp+=q.top();q.pop();ans+=tmp;q.push(tmp);}return ans;- if (n < 2) return 0;
- int* end = a+n;
- int sum = 0;
- while (end > a+1)
- {
- std::make_heap(a, end, greater<int>());
- std::pop_heap(a, end, greater<int>());
- --end;
- sum += (*a += *end);
- }
- return sum;
- }
// TODO: Replace examples and use TDD development by writing your own tests Describe(any_group_name_you_want) { It(should_do_something) { { Assert::That(apple(0,0), Equals(0)); } { int a[]={3}; Assert::That(apple(1,a), Equals(0)); } { int a[]={3,5}; Assert::That(apple(2,a), Equals(8)); } { int a[]={6,5}; Assert::That(apple(2,a), Equals(11)); } { int a[]={1,2,3}; Assert::That(apple(3,a), Equals(9)); } { int a[]={1,2,3,4}; Assert::That(apple(4,a), Equals(19)); } { int a[]={3,2,1,4}; Assert::That(apple(4,a), Equals(19)); } { int a[]={3,5,1}; Assert::That(apple(3,a), Equals(13)); } { int a[]={1,2,3,4}; Assert::That(apple(4,a), Equals(19)); } { int b[]={3,5,2,1,4}; Assert::That(apple(5,b), Equals(33)); } } };
- // TODO: Replace examples and use TDD development by writing your own tests
- Describe(any_group_name_you_want)
- {
- It(should_do_something)
- {
- {
- Assert::That(apple(0,0), Equals(0));
- }
- {
- int a[]={3};
- Assert::That(apple(1,a), Equals(0));
- }
- {
- int a[]={3,5};
- Assert::That(apple(2,a), Equals(8));
- }
- {
- int a[]={6,5};
- Assert::That(apple(2,a), Equals(11));
- }
- {
- int a[]={1,2,3};
- Assert::That(apple(3,a), Equals(9));
- }
- {
- int a[]={1,2,3,4};
- Assert::That(apple(4,a), Equals(19));
- }
- {
- int a[]={3,2,1,4};
- Assert::That(apple(4,a), Equals(19));
- }
- {
- int a[]={3,5,1};
- Assert::That(apple(3,a), Equals(13));
- }
- {
- int a[]={1,2,3,4};
- Assert::That(apple(4,a), Equals(19));
- }
- {
- int b[]={3,5,2,1,4};
- Assert::That(apple(5,b), Equals(33));
- }
- }
- };