数据结构——哈夫曼树

可参考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;
}
相关推荐
码银6 小时前
【数据结构】顺序表
java·开发语言·数据结构
小张成长计划..7 小时前
【C++】List容器的理解和使用(超详细)
数据结构·list
尼古拉斯·纯情暖男·天真·阿玮10 小时前
泛型与数据结构
java·数据结构
wefg110 小时前
【数据结构】unordered 系列容器底层结构和封装
数据结构·算法·哈希算法
遗憾是什么.10 小时前
数据结构 - - 队列
数据结构
DARLING Zero two♡10 小时前
【优选算法】LinkedList-Concatenate:链表的算法之契
数据结构·c++·算法·链表
大袁同学11 小时前
【二叉搜索树】:程序的“决策树”,排序数据的基石
数据结构·c++·算法·决策树·stl
Algo-hx12 小时前
数据结构入门 (十):“左小右大”的秩序 —— 深入二叉搜索树
数据结构·算法
Ace_317508877613 小时前
京东商品详情接口深度解析:从反爬绕过到数据结构化重构
数据结构·python·重构