贪心-哈夫曼树——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;
}
相关推荐
生态学者20 分钟前
Global Change Biology | 森林越“步调一致”,反而越怕干旱?树木生长与叶片活动的同步之谜
大数据·人工智能·算法·r语言·微信公众平台
lsswear1 小时前
Agent 框架新手入门与实战部署指南
大数据·人工智能·算法
Data analyse4562 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
Navigator_Z4 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2084 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年4 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.3335 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
Nil2085 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
神工坊5 小时前
技术分享︱SIMFORGE HSF® 网格加密与热点加速技术实践
算法·hpc·网格·cae·工程仿真·数值引擎·samr
CV@CV6 小时前
世界模型与智能体协同推理逻辑
人工智能·算法·边缘计算·量子计算·具身智能