哈夫曼编码(贪心算法)

#include<iostream>
#include<string>
#include<queue>
using namespace std;
class node
{
public:
    node(string a, float wht, node* left, node* right, string b)
    {
        content=a;
        weight=wht;
        leftchild=left;
        rightchild=right;
        code=b;
    }
    string content;
    float weight;
    node* leftchild;
    node* rightchild;
    string code;
};
void so(node** array, int low, int high)
{
    for(int i=low+1;i<high;i++)
	{
        node* tem=array[i];
        int j=i-1;
        while(array[j]->weight>tem->weight&&j>=low)
		{
            array[j+1]=array[j];
            j--;
        }
        array[j+1]=tem;
	}
}
void createtree(string* s, float* w,int n,node** array)
{
    for(int i=0;i<n;i++)
	{
        array[i]=new node(s[i],w[i],NULL,NULL,"");
    }
	so(array,0,n);
	int p=0;
    while(p!=n-1)
	{
        node* min_1=array[p];
        node* min_2=array[p+1];
        node* new_node=new node("",min_1->weight+min_2->weight,min_1,min_2,"");
        array[p+1]=new_node;
        p=p+1;
		so(array,0,n);
    }

}
void code(node* p)
{
    queue<node*> nq;
    nq.push(p);
    while(nq.size()!=0)
	{
        node* cur=nq.front();
        nq.pop();
        node* l=cur->leftchild;
        if(l!=NULL)
		{
			l->code=cur->code+"0";
			nq.push(l);
		}
        node* r=cur->rightchild;
        if(r!=NULL)
		{
			r->code=cur->code+"1";
			nq.push(r);
		}
        if(l==NULL&&r==NULL)
		{
            cout<<cur->content<<": "<<cur->code<<endl;
         }
    }
}
int main()
{
     node* array[8];
     string s[8]={"a","b","c","d","e","f","g","h"};
     float w[8]={1,1,2,3,5,8,13,21};
     createtree(s,w,8,array);
     code(array[7]);
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值