哈夫曼编码(Huffman)

 

今天看数据结构,看到哈夫曼编码。感觉挺有意思的。哈夫曼树的应用应该很多吧,还刚学,以后多深入看看。

 

#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <queue>
//#include <functional>
#include <cstring>
#define Max 100000000
using namespace std;
struct node
{
    int ww;
    int parent,left,right;
};
struct pp
{
    int m;
    int root;
    node head[100];
};
int x[50];
string y[50];
pp Huffman(int m)
{
    pp shu;
    shu.m=m;
    int m1=Max,m2=Max;
    for (int number=0;number<2*m-1;number++)
    {
        shu.head[number].ww=-1,shu.head[number].parent=-1,shu.head[number].left=-1,
        shu.head[number].right=-1;
        if(number<m)
        {
            shu.head[number].ww=x[number];
        }
    }
    for (int number1=0;number1<m-1;number1++)
    {
        int x1=-1,x2=-1;
        m1=Max,m2=Max;
        for (int number2=0;number2<number1+m;number2++)
        {
            if (shu.head[number2].ww<m1&&shu.head[number2].parent==-1)
            {
                x2=x1,m2=m1;
                x1=number2;
                m1=shu.head[number2].ww;
            }
            else if (shu.head[number2].ww<m2&&shu.head[number2].parent==-1)
            {
                x2=number2;
                m2=shu.head[number2].ww;
            }
        }
        shu.head[x1].parent=m+number1;
        shu.head[x2].parent=m+number1;
        shu.head[m+number1].left=x1;
        shu.head[m+number1].right=x2;
        shu.head[m+number1].ww=m1+m2;
    }
    return shu;

}
void qian(pp shu,int num,string all)
{
    string p=all;
    int flag=0;
    if (shu.head[num].left!=-1)
    {
        flag=1;
        all+='0';
        qian(shu,shu.head[num].left,all);
    }
    if (shu.head[num].right!=-1)
    {
        if (flag==1)all=p;
        all+='1';
        qian(shu,shu.head[num].right,all);
    }
    if (shu.head[num].left==-1&&shu.head[num].right==-1)
    {
        y[num]=all;
    }
}//用来输出哈夫曼编码的。


 

转载于:https://www.cnblogs.com/GregZQ/p/8365312.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值