LintCode 3209: Moving fruit 堆典型题

本文介绍了一种使用最小能量将分散的水果堆合并为一堆的高效算法。通过优先队列实现,每次选取两个最小的堆进行合并,直至所有堆合并完成。此方法适用于需要优化搬运成本的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值