数据结构——哈夫曼树

可参考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;
}
相关推荐
商bol455 分钟前
习题与正则表达式
数据结构·c++·算法
clock的时钟2 小时前
数据结构(一)KMP+滑动窗口+链表+栈+队列
数据结构·算法·链表
sugar__salt2 小时前
各种排序思路及实现
数据结构·算法·排序算法
Vitalia2 小时前
⭐算法OJ⭐数据流的中位数【最小堆】Find Median from Data Stream
数据结构·c++·算法·最小堆
阿巴~阿巴~3 小时前
二分 —— 基本算法刷题路程
数据结构·c++·算法
maomi_95264 小时前
《线性表、顺序表与链表》教案(C语言版本)
c语言·数据结构·链表
Run_Teenage4 小时前
C语言 数据结构 【队列】动态模拟实现
数据结构
蒙奇D索大4 小时前
【数据结构】邻接矩阵完全指南:原理、实现与稠密图优化技巧
c语言·数据结构·考研·图论·改行学it
半桔4 小时前
哈希表(开散列)的实现
数据结构·c++·面试·散列表·哈希
牛奶咖啡.8546 小时前
树和图论(详细整理,简单易懂!)
数据结构·c++·算法·深度优先·图论