优先队列解决哈夫曼编码问题
2016-03-19 22:53
465 查看
#include<iostream> using namespace std; class Heap { private: int *data, size; public: Heap(int length_input) { data = new int[length_input]; size = 0; } ~Heap() { delete[] data; } void push(int value) { data[size] = value; int current = size; int father = (current - 1) / 2; while (data[current] < data[father]) { swap(data[current], data[father]); current = father; father = (current - 1) / 2; } size++; } int top() { return data[0]; } void update(int pos, int n) { int lchild = 2 * pos + 1, rchild = 2 * pos + 2; int max_value = pos; if (lchild < n && data[lchild] < data[max_value]) { max_value = lchild; } if (rchild < n && data[rchild] < data[max_value]) { max_value = rchild; } if (max_value != pos) { swap(data[pos], data[max_value]); update(max_value, n); } } void pop() { swap(data[0], data[size - 1]); size--; update(0, size); } int heap_size() { return size; } }; int main() { int n,value,ans=0; cin>>n; Heap heap(n); for(int i=1;i<=n;++i) { cin>>value; heap.push(value); } if(n==1) { ans+=heap.top(); } while(heap.heap_size()> 1) { int a=heap.top(); heap.pop(); int b=heap.top(); heap.pop(); ans=ans+a+b; heap.push(a+b); } cout<<ans<<endl; return 0; }
相关文章推荐
- hdu4057(AC自动机+状态压缩dp)
- LINUX安装JDK1.6
- 7对数字排序
- 第三周学习进度条
- 学习进度条
- 大道至简 读书笔记01
- LVS 服务器集群三种实现模式配置
- 【2016/1】 Unix IPC 信号 共享内存 消息队列
- docker基础命令详解
- 求2个字符串的最长公共子串——矩阵法
- Could not decode a text frame as UTF-8 的解决
- 使用Ext.widget()方法时弹出错误的问题
- 应项目需要,弄了个多文件上传,分享给大家,求指正,共进步
- codeforces 653B B. Bear and Compressing(dfs)
- Hibernate逍遥游记-第4章映射对象标识符-increment、identity、hilo、native、assigned、sequence、<meta>
- mysql连接问题
- git osc 体验
- 腾讯产品总监:我工作十年,内心仍无比恐慌
- BestCoder Round #76
- FEDay第二届前端开发者大会后记