贪心:Huffman树

合并果子:

该题与石子合并的区别:石子合并是两两相邻才能合并,这题是任意两点合并

该题的思路:每次合并最小的两个点

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

int main()
{
    int n;
    scanf("%d", &n);

    priority_queue<int, vector<int>, greater<int>> heap;//小根堆,所以堆头是最小值
    while (n -- )
    {
        int x;
        scanf("%d", &x);
        heap.push(x);
    }

    int res = 0;//答案
    while (heap.size() > 1)//只要超过两个数,就两个合并。因为是小根堆,每次合并的都是最小的两个
    {
        int a = heap.top(); heap.pop();
        int b = heap.top(); heap.pop();
        res += a + b;
        heap.push(a + b);
    }

    printf("%d\n", res);
    return 0;
}
相关推荐
lisw057 小时前
稀疏算法概述!
算法·机器人·无人机
思想觉悟8 小时前
Aosp实战之自定义开机启动进程
c++·面试
YLCHUP8 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴9 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu13 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu14 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
derek199715 小时前
软考软件设计师:主键、传递依赖和冗余,三问其实是一件事
c语言·c++·计算机网络·软件工程·学习方法
凌冰_16 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏16 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
艾莉丝努力练剑16 小时前
【AI大模型接入SDK】解决Unicode码转化以及界面变形问题
前端·c++·人工智能·学习·安全·架构