数据结构——哈夫曼树

可参考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 小时前
单链表和双向链表
数据结构·链表
Orlando cron2 小时前
数据结构入门:链表
数据结构·算法·链表
许愿与你永世安宁7 小时前
力扣343 整数拆分
数据结构·算法·leetcode
Heartoxx8 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼9 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
学不动CV了18 小时前
数据结构---线性表理解(一)
数据结构
ysa05103019 小时前
数论基础知识和模板
数据结构·c++·笔记·算法
今天背单词了吗98019 小时前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法
气质、小青年!19 小时前
【排序算法】
c语言·数据结构
clock的时钟21 小时前
暑期数据结构第一天
数据结构·算法