贪心-哈夫曼树——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;
}
相关推荐
月明长歌1 分钟前
【码道初阶-Hot100】LeetCode 3. 无重复字符的最长子串:从错误直觉到滑动窗口,彻底讲透为什么必须判断 `map.get(c) >= left`
java·算法·leetcode·哈希算法
junnhwan3 分钟前
LeetCode Hot 100——贪心算法
java·算法·leetcode
魑魅魍魉都是鬼4 分钟前
java 的排序算法
java·算法·排序算法
2401_853576505 分钟前
并行算法在STL中的应用
开发语言·c++·算法
晓纪同学5 分钟前
ROS2 -06-动作
java·数据库·python·算法·机器人·ros·ros2
无限进步_6 分钟前
【C++】字符串中的字母反转算法详解
开发语言·c++·ide·git·算法·github·visual studio
qyzm6 分钟前
Codeforces Round 927 (Div. 3)
数据结构·python·算法
2401_891482177 分钟前
C++中的状态模式实战
开发语言·c++·算法
Frostnova丶9 分钟前
LeetCode 1727.重新排列后的最大子矩阵
算法·leetcode
自信1504130575910 分钟前
数据结构之二叉树算法题
c语言·数据结构·算法