• 哈夫曼树


    #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
    ", b[i].idx, b[i].l, b[i].weight, b[i].r, b[i].parent);
        return 0;
    }
    

      

  • 相关阅读:
    python学习之模块补充二
    MySQL的表关系
    初识数据库
    MySQL基础
    死锁 递归锁 信号量 Event事件 线程q
    进程池/线程池与协程
    线程
    进程相关知识点
    python 之多进程
    socket 基础
  • 原文地址:https://www.cnblogs.com/NDKY9/p/7820075.html
Copyright © 2020-2023  润新知