数据结构——哈夫曼树

可参考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;
}
相关推荐
码农多耕地呗1 小时前
力扣146.LRU缓存(哈希表缓存.映射+双向链表数据结构手搓.维护使用状况顺序)(java)
数据结构·leetcode·缓存
晚枫~2 小时前
数据结构基石:从线性表到树形世界的探索
数据结构
hadage2332 小时前
--- 数据结构 AVL树 ---
数据结构·算法
liu****2 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛2 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
学编程就要猛4 小时前
数据结构初阶:时间和空间复杂度
数据结构
Chloeis Syntax6 小时前
接10月12日---队列笔记
java·数据结构·笔记·队列
草莓工作室8 小时前
数据结构7:栈和队列
c语言·数据结构
小欣加油8 小时前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表
Camel卡蒙8 小时前
数据结构——字典树Trie(介绍、Java实现)
java·数据结构