3209 · Moving fruit
C++
Medium
This topic is a pre-release topic. If you encounter any problems, please contact us via “Problem Correction”, and we will upgrade your account to VIP as a thank you.
Description
Xiao Ming came to the orchard to pick fruits, and when he finished picking, the fruits were divided into several piles.
Now Xiao Ming wants to combine these fruits into a pile. Please design an algorithm so that Xiao Ming consumes the least amount of energy to carry the fruits.
Note:
It takes 1 point of energy to carry 1 fruit.
Only two piles of fruit can be combined at a time.
Example:
If you want to move 1 3 8 piles of fruits, the most energy efficient way is to.
First move 1 3 together, consume 4 points, and now the fruit becomes two piles of 4 8.
Then move 4 8 together, consume 12 points of energy, and now the fruit is only 12 piles.
In total, 4 + 12 of 16 points are consumed.
This function.
Receives a vector container fruits that stores shaped data indicating how many fruits are in each pile in turn.
Returns an int integer indicating the total amount of energy required to carry the piles together.
This question requires you to complete the code in the function carry in the file Solution.cpp.
The evaluator will run main.cpp to call the carry function in Soluction.cpp by importing a custom function library and get your return value to determine the correctness of the result.
The topic guarantees that the final value of stamina consumed for the given data is within the data range of int.
Use the automatic sorting feature of the collection container in the library to solve the problem.
Duplicate elements can occur in both data and merge processes.
Example
Input Sample 1:
[2,2,3,3,6]
Output sample 1:
36
The most effortless way to carry is.
2 + 2 = 4 -> 4,3,3,6
3 + 3 = 6 -> 4,6,6
4 + 6 = 10 -> 10,6
6 + 10 = 16 -> 16
4 + 6 + 10 + 16 = 36
Input sample 2:
[]
Output sample 2:
0
There is no fruit to carry, so the stamina consumption is 0.
解法1:
#include <queue>
/**
* @param fruits: An arryy
* @return: An integer
*/
int carry(vector<int> &fruits) {
int len = fruits.size();
if (len == 0) return 0;
if (len == 1) return fruits[0];
int sum = 0;
priority_queue<int, vector<int>, greater<int>> minHeap(fruits.begin(), fruits.end());
while (minHeap.size() > 1) {
int min1 = minHeap.top();
minHeap.pop();
int min2 = minHeap.top();
minHeap.pop();
sum += min1 + min2;
minHeap.push(min1 + min2);
}
return sum;
}
本文介绍了一种使用最小能量将分散的水果堆合并为一堆的高效算法。通过优先队列实现,每次选取两个最小的堆进行合并,直至所有堆合并完成。此方法适用于需要优化搬运成本的场景。
6488

被折叠的 条评论
为什么被折叠?



