数据结构——哈夫曼树

可参考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;
}
相关推荐
Liu_Meihao37 分钟前
【算法】799. 最长连续不重复子序列
数据结构·算法
正在敲代码中1 小时前
变换队列c++
数据结构·c++·算法
yonuyeung4 小时前
代码随想录算法【Day57】
数据结构·算法
graceyun4 小时前
初阶数据结构(C语言实现)——3顺序表和链表(2)
c语言·数据结构·链表
非衣居士5 小时前
游戏编程模式(28种编程模式)
数据结构·游戏开发
Fms_Sa5 小时前
将两个有序链表合并成一个有序链表
数据结构·链表
查理零世6 小时前
【数据结构】 最大最小堆实现优先队列 python
数据结构·python
小喵要摸鱼6 小时前
【Python 语法】Python 数据结构
数据结构·python
程序猿看视界7 小时前
「读书计划」《啊哈!算法》7日结构化学习规划
数据结构·编程·算法竞赛·学习计划·算法学习