码迷,mamicode.com
首页 > 其他好文 > 详细

非递归建立哈夫曼树

时间:2017-11-11 22:10:29      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:begin   bool   stream   highlight   parent   递归   哈夫曼树   log   ras   

#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;
}

  

非递归建立哈夫曼树

标签:begin   bool   stream   highlight   parent   递归   哈夫曼树   log   ras   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!