当前位置:网站首页>3531. 哈夫曼树
3531. 哈夫曼树
2022-08-08 16:41:00 【NEFU AB-IN】
Powered by:NEFU AB-IN
文章目录
3531. 哈夫曼树
题意
给定 N 个权值作为 N 个叶子结点,构造一棵二叉树,若该树的带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman Tree)。
现在,给定 N 个叶子结点的信息,请你构造哈夫曼树,并输出该树的带权路径长度。
相关知识:
1、路径和路径长度
在一棵树中,从一个结点往下可以达到的孩子或孙子结点之间的通路,称为路径。通路中分支的数目称为路径长度。若规定根结点的层数为 1,则从根结点到第 L 层结点的路径长度为 L−1。
2、结点的权及带权路径长度
若将树中结点赋给一个有着某种含义的数值,则这个数值称为该结点的权。结点的带权路径长度为:从根结点到该结点之间的路径长度与该结点的权的乘积。
3、树的带权路径长度
树的带权路径长度规定为所有叶子结点的带权路径长度之和,记为 WPL。思路
注意给的是:N个叶子结点(而不是合成结点),其实也就相当于合并果子里的果子,一步一步挑最小的结点进行合成
代码
/* * @Author: NEFU AB-IN * @Date: 2022-08-07 20:13:36 * @FilePath: \Acwing\3531\3531.cpp * @LastEditTime: 2022-08-07 21:36:05 */ #include <bits/stdc++.h> using namespace std; #define int long long #define SZ(X) ((int)(X).size()) #define IOS \ ios::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) #define DEBUG(X) cout << #X << ": " << X << '\n' typedef pair<int, int> PII; const int INF = INT_MAX; const int N = 1e6 + 10; signed main() { IOS; int n; cin >> n; priority_queue<int, vector<int>, greater<int>> q; for (int i = 1; i <= n; ++i) { int x; cin >> x; q.push(x); } int res = 0; while (SZ(q) > 1) { auto t1 = q.top(); q.pop(); auto t2 = q.top(); q.pop(); res += t1 + t2; q.push(t1 + t2); } cout << res << '\n'; return 0; }
边栏推荐
- 2020年适用于Linux的10个顶级开源缓存工具
- MySQL数据库的简介及select语句的执行流程
- 使用 Pygame 构建和可视化数独游戏
- 【8.7】代码源 - 【抽卡】【LCM与GCD】
- 使用 ansible-bender 构建容器镜像
- 差分约束做法
- iNFTnews | Metaverse brings new ideas for enterprise development
- 题目:有序队列
- 【LeetCode】试题总结:深度优先搜索 (DFS)
- 9. cuBLAS Development Guide Chinese Version--Configuration of Atomic Mode in cuBLAS
猜你喜欢
Kubernetes资源编排系列之四: CRD+Operator篇
3dsmax2021软件安装教程
使用 FasterTransformer 和 Triton 推理服务器加速大型 Transformer 模型的推理
Digital image processing (6) -- image compression
APICloud AVM wraps date and time selection components
APICloud AVM 封装日期和时间选择组件
linux安装部署redis&配置远程连接
The realization of the salary slip issuing function of WeChat public account + web background
ctfshow七夕杯复现
差分约束做法
随机推荐
Subject: Ordered Queue
智能指针学习笔记
synchronized加载static关键字前和普通方法前的区别?
iNFTnews | 元宇宙为企业发展带来新思路
Spam accounts are a lot of trouble, and device fingerprints are quickly found
R语言(数值、列表、矩阵)上应用函数(sqrt、round、mean、log)、将矩阵所有数据求对数、就矩阵整体的均值、使用apply函数计算矩阵matrix的行均值、列均值、trim设置返回结果精度
Charles MOCK 数据 htpps代理
基于华为云ModelArts的水表读数识别开发实践【华为云至简致远】
Web3构架是怎么样的?
DASCTF部分复现
【LeetCode】试题总结:深度优先搜索 (DFS)
ASP.NET Core依赖注入之旅:4.体验服务的注册和消费
laravel - 查询构建器2
laravel-practice
redis设计与实现 笔记(一)
【LeetCode】Exam Summary: Depth-First Search (DFS)
基于ECS实现一分钟自动化部署【华为云至简致远】
The situation of the solution of the equation system and the correlation transformation of the vector group
IDEA2020安装教程
ctfshow七夕杯复现