数据结构——哈夫曼树

可参考priority_queue(优先队列)讲解_priority------queue-CSDN博客

例题148. 合并果子 - AcWing题库

用优先队列(堆-完全二叉树)来实现哈夫曼树,每次取小根堆队头两元素相加为一个,pop完再push进去,相当于模拟哈夫曼树的构造了。

代码如下:

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;
#define fs first
#define sc second
#define endl '\n'
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> PII;

void solve(){
    priority_queue<int,vector<int>,greater<int>> q;//小根堆
    
    int n;cin>>n;
    
    for(int i=0;i<n;i++)
    {
        int x;cin>>x;
        q.push(x);
    }
    
    int ans=0;
    
    while(q.size()>1)
    {
    	//取最小的两个元素
        int a=q.top();q.pop();
        int b=q.top();q.pop();
        ans+=(a+b);
        q.push(a+b);
    }
    
    cout<<ans<<endl;
}

int main(){
	
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);

    int t;
    t=1;

    while (t--)
    {
        solve();
    }
    
    return 0;
}
相关推荐
a.3027 分钟前
C++ 时间处理指南:深入剖析<ctime>库
数据结构·c++·算法
圈圈编码6 小时前
LeetCode Hot100刷题——合并两个有序链表
java·数据结构·算法·leetcode·链表
jingfeng5147 小时前
详解快排的四种方式
数据结构·算法·排序算法
蒙奇D索大9 小时前
【数据结构】图论最短路径算法深度解析:从BFS基础到全算法综述
数据结构·算法·图论·广度优先·图搜索算法
AL流云。13 小时前
【优选算法】分治
数据结构·算法·leetcode·排序算法
行驶14 小时前
数据结构 - 栈与队列
数据结构
haoly198914 小时前
数据结构篇--分离链表vs线性探测
数据结构
小贾要学习14 小时前
【数据结构】AVL树的实现
数据结构
andyweike14 小时前
数据结构-文件
数据结构
andyweike14 小时前
数据结构-线性表
数据结构