首页 > 其他 > 详细

非递归建立哈夫曼树

时间:2017-11-11 22:05:04      阅读:331      评论:0      收藏:0      [点我收藏+]
#include<vector>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
 
struct HT
{
    int weight, parent, l, r, idx;
};
bool cmp(HT a, HT b)
{
    return a.weight < b.weight;
}
int main()
{
    int n;
    vector<HT>a, b;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        HT x;
        cin >> x.weight;
        x.idx = i;
        x.parent = -1;
        x.l = -1;
        x.r = -1;
        a.push_back(x);
        b.push_back(x);
    }
 
    while (a.size() != 1)
    {
        sort(a.begin(), a.end(), cmp);
        HT x;
        x.idx = b.size();
        x.weight = a[0].weight + a[1].weight;
        x.l = a[0].idx;
        x.r = a[1].idx;
        for (int i = 0; i < b.size(); i++)
        {
            if (b[i].idx == x.l || b[i].idx == x.r)
                b[i].parent = x.idx;
        }
        a.push_back(x);
        a.erase(a.begin());
        a.erase(a.begin());
        b.push_back(x);
    }
    b[b.size() - 1].parent = -1;
    for (int i = 0; i < b.size(); i++)
        printf("%d %d %d %d %d\n", b[i].idx, b[i].l, b[i].weight, b[i].r, b[i].parent);
    return 0;
}

  

非递归建立哈夫曼树

原文:http://www.cnblogs.com/NDKY9/p/7820075.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!