贪心: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;
}
相关推荐
伊玛目的门徒31 分钟前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry1 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵2 小时前
【无标题】
数据结构·算法
Kx_Triumphs4 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎4 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
Darkwanderor5 小时前
对Linux的进程控制的研究
linux·运维·c++
云泽8085 小时前
从零吃透 C++ 异常:抛出捕获、栈展开、异常重抛与编码规范详解
开发语言·c++·代码规范
轻颂呀5 小时前
约瑟夫环问题
算法
REDcker5 小时前
libdatachannel 快速入门
c++·webrtc·datachannel