zoukankan      html  css  js  c++  java
  • Huffman编码

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    //#pragma warning(disable:4996)
    
    using namespace std;
    
    typedef char **HuffmanCode;
    
    typedef struct{
        int weight;
        int parent, lchild, rchild;
    }HTNode, *HuffmanTree;
    
    
    void Select(HuffmanTree HT, int n, int &s1, int &s2)
    {
        int min1 = 100000, min2 = min1;
        for (int i = 1; i <= n; i++)
        {
            if (HT[i].weight <= min1 && HT[i].parent == 0)
            {
                min1 = HT[i].weight;
                s1 = i;
            }
        }
        HT[s1].parent = -1;
        for (int i = 1; i <= n; i++)
        {
            if (HT[i].weight <= min2 && HT[i].parent == 0)
            {
                min2 = HT[i].weight;
                s2 = i;
            }
        }
    }
    
    void CreatHuffmanTree(HuffmanTree &HT, int n)
    {
        if (n <= 1) return;
        int m = 2 * n - 1, s1, s2;
        HT = new HTNode[m + 1];
        for (int i = 1; i <= m; ++i)
        {
            HT[i].lchild = 0;
            HT[i].rchild = 0;
            HT[i].parent = 0;
        }
        for (int i = 1; i <= n; ++i)
            cin >> HT[i].weight;
        for (int i = n + 1; i <= m; ++i)
        {
            Select(HT, i - 1, s1, s2);
            HT[s1].parent = HT[s2].parent = i;
            HT[i].lchild = s1;
            HT[i].rchild = s2;
            HT[i].weight = HT[s1].weight + HT[s2].weight;
        }
    }
    
    void CreatHuffmanCode(HuffmanTree HT, HuffmanCode &HC, int n)
    {
        HC = new char*[n + 1];
        char *cd= new char[n];
        cd[n - 1] = '';
        for (int i = 1; i <= n; ++i)
        {
            int start = n - 1, c = i, f = HT[i].parent;
            while (f != 0)
            {
                --start;
                if (HT[f].lchild == c)
                    cd[start] = '0';
                else
                    cd[start] = '1';
                c = f;
                f = HT[f].parent;
            }
            HC[i] = new char[n - start];
            strcpy(HC[i], &cd[start]);
        }
        delete[] cd;
    }
    
    int main()
    {
        int n;
        HuffmanTree HT;
        HuffmanCode HC;
        cout << "根据n个权值{ W1,W2....Wn }构造哈夫曼树.
    ";
        cout << "输入权值个数n: ";
        cin >> n;
        cout << "输入n个权值:";
        CreatHuffmanTree(HT, n);
        CreatHuffmanCode(HT, HC, n);
        cout << "这n个权值的哈夫曼编码为:
    ";
        for (int i = 1; i <= n; i++)
            cout << HC[i] << endl;
        return 0;
    }

    运行结果:

  • 相关阅读:
    Linux文件管理详解
    Linux用户管理详解
    Error: No suitable device found: no device found for connection "System eth0" 解决方法
    Linux配置网络详解
    万能的数据传输格式XML入门教程
    【万能的数据传输格式XML入门教程】八、Xpath查询语言
    【万能的数据传输格式XML入门教程】七、SimpleXML模型(查询操作)
    h5标签兼容
    vue 常用指令
    echarts3更新
  • 原文地址:https://www.cnblogs.com/cjwen/p/11177101.html
Copyright © 2011-2022 走看看