算法题(154):合并果子
审题:
本题需要我们找到多多消耗的最小体力值思路:
方法一:哈夫曼树由于题目中说多多最终需要把很多堆的果子移动为一堆(类似哈夫曼树的构建过程),且他消耗的体力是移动果子的重量之和,消耗的体力值需要最小(符合哈夫曼树的带权路径计算,哈夫曼树可以让带权路径和最小)
解题:
#include<iostream> #include<vector> #include<queue> using namespace std; typedef long long ll; int n; priority_queue<ll,vector<ll>,greater<ll>> a; int main() {//数据录入cin >> n;for (int i = 1; i <= n; i++){ll x = 0;cin >> x;a.push(x);}//哈夫曼树构造ll answer = 0;while (a.size() != 1){ll b = a.top(); a.pop();ll c = a.top(); a.pop();answer += b + c;a.push(b + c);}cout << answer << endl;return 0; }
本题没有需要改动的地方,和模板题哈夫曼编码基本一致,所以不做详细讲解
P1090 [NOIP 2004 提高组] 合并果子 - 洛谷