贪心-哈夫曼树——acwing

题目:合并果子

148. 合并果子 - AcWing题库

分析

典型的哈夫曼树。也是最优二叉树,是一类带权路径长度最短的树。每次取两个最小的,合并成新的。

其实就是贪心,因为合并次数是固定的,每次都取最小能保证答案最小。

思考存储结构就是 能让最小的在前面就行,可以小根堆,也可以multiset

代码 1(multiset容器)

用multiset容器来存储数据,自动排序,目的是为了让最小的在最前面。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

multiset<int> s;

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i ++) {
        int x; cin >> x;
        s.insert(x);
    }
    int res = 0;
    for(int i = 0; i < n-1; i ++) {
        set<int>::iterator it;
        it = s.begin();
        int a = *it; s.erase(s.begin());
        it = s.begin();
        int b = *it; s.erase(s.begin());
        res += (a+b);
        s.insert(a+b);
    }
    cout << res << endl;
    return 0;
}

代码2(小根堆)

取最值问题可以用到小根堆或者大根堆

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

priority_queue<int,vector<int>,greater<int>> h;

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i ++) {
        int x; cin >> x;
        h.push(x);
    }
    
    int res = 0;
    while(h.size()>1) {
        auto a = h.top(); h.pop();
        auto b = h.top(); h.pop();
        res += (a+b);
        h.push(a+b);
    }
    cout << res << endl;
    return 0;
}
相关推荐
开源Z21 分钟前
LeetCode 42 · 接雨水:从暴力到双指针的三步优化
算法·leetcode
旖-旎30 分钟前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill
syagain_zsx1 小时前
STL 之 vector 讲练结合
c++·算法
MartinYeung52 小时前
[论文学习]DP2Unlearning:高效且具保证的大型语言模型遗忘框架(基于差分隐私的 LLM Unlearning 方法)
学习·算法·语言模型
Tian_Hang3 小时前
C++原型模式(Protype)
开发语言·c++·算法
bIo7lyA8v3 小时前
算法复杂度的渐进分析与实际运行时间的差异的技术8
算法
yuan199974 小时前
欧拉梁静力与屈曲计算的 MATLAB 实现(有限差分法 + 解析解)
开发语言·算法·matlab
汉克老师4 小时前
GESP7级C++考试语法知识(二、指数函数(3、综合练习)
c++·算法·数学建模·指数函数·gesp7级·复利
Seraphina_Lily5 小时前
深入C语言底层:隐式类型转换、整数提升与截断的“致命”陷阱
c语言·开发语言·算法