贪心-哈夫曼树——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;
}
相关推荐
YuTaoShao几秒前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0078 分钟前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
风暴之零18 分钟前
变点检测算法PELT
算法
深鱼~18 分钟前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann
李斯啦果19 分钟前
【PTA】L1-019 谁先倒
数据结构·算法
梵刹古音24 分钟前
【C语言】 指针基础与定义
c语言·开发语言·算法
啊阿狸不会拉杆41 分钟前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
R1nG8631 小时前
CANN资源泄漏检测工具源码深度解读 实战设备内存泄漏排查
数据库·算法·cann
_OP_CHEN2 小时前
【算法基础篇】(五十六)容斥原理指南:从集合计数到算法实战,解决组合数学的 “重叠难题”!
算法·蓝桥杯·c/c++·组合数学·容斥原理·算法竞赛·acm/icpc
TracyCoder1232 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode