基于双队列实现huffman树

来源:互联网 发布:郑州财经学院网络下线 编辑:程序博客网 时间:2024/05/22 14:32

今天数算课讲huffman树,是基于堆实现的,突然想起以前实现过基于双队列的huffman树,做个回顾。

首先将n个元素从小到大排序,基于比较的排序都是nlogn的复杂度,这里可以考虑用计数排序(即桶排序)或者基数排序尝试优化到n试试。

然后我们获得了一个有序队列我们把它放在A队列中,然后再找一个空的B队列。

然后从A中或者B中找出两个最小的元素,累加放入B队列的队尾加入。不难发现B队列也是递增的。这样模拟每次取最小的两个。

仔细一想,原先需用插入堆中,动态询问最小值的问题,被我们用双队列取代了,之所以能用双队列实现,

因为这个问题特殊在它每次产生的新的数是由两个最小的数产生的,这样使得产生的值都是递增的。因此才可以用双队列去优化它。

// 双队列实现huffman树#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <queue>using namespace std;const int MAXN = 100+5;int test,n,a[MAXN];queue<int> qa,qb;int get(){int t;if (qb.empty()){t = qa.front(); qa.pop();return t;}if (qa.empty()){t = qb.front(); qb.pop();return t;}if (qa.front() < qb.front()) {t = qa.front(); qa.pop();} else {t = qb.front(); qb.pop();}return t; }int main(){cin>>test;while (test--){cin>>n;while (!qa.empty()) qa.pop();while (!qb.empty()) qb.pop();for (int i = 1; i <= n; ++i)cin>> a[i];sort(a+1,a+n+1); // 可以尝试用基数排序优化这部分时间复杂度for (int i = 1; i <= n; ++i) qa.push(a[i]);int sum = 0;for (int i = 1; i < n; ++i) {int t1 = get();int t2 = get();sum += (t1+t2);qb.push(t1+t2);}cout << sum << endl;}return 0;}


原创粉丝点击