Huffman树

#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
#include<queue>

using namespace std;
struct HufTree
{
    char data;
    int weight;
    string code;
    HufTree*left,*right;
    HufTree(char d,int w):data(d),weight(w),code(""),left(0),right(0){}
};
struct cmp
{
    bool operator() (HufTree* a ,HufTree* b)
    {
        return a->weight>b->weight;      //与less是等价的
    }
};
struct cmpGreat
{
    bool operator() (HufTree* a ,HufTree* b)
    {
        return a->weight<b->weight;      //与greater是等价的
    }
};
void update0(HufTree*&root)
{
    if(!root)
        return;
    root->code="0"+root->code;
    update0(root->left);
    update0(root->right);
}
void update1(HufTree*&root)
{
    if(!root)
        return;
    root->code="1"+root->code;
    update1(root->left);
    update1(root->right);
}
priority_queue<HufTree*,vector<HufTree*>,cmpGreat> out;
void levelTra(HufTree*root)
{
    if(!root)
        return;
    queue<HufTree* > q;
    q.push(root);
    while(!q.empty())
    {
        HufTree*pt=q.front();
        if(!pt->left&&!pt->right)
            out.push(pt);
        q.pop();
        if(pt->left)
            q.push(pt->left);
        if(pt->right)
            q.push(pt->right);
    }
}
int cont[120];
int main()
{
    int num;
    char code;
    cin>>num;
    while(num--)
    {
        cin>>code;
        cont[code]++;
    }
    priority_queue<HufTree*,vector<HufTree*>,cmp> pq;
    for(char i='A';i<='Z';i++)
        if(cont[i]!=0)
            pq.push(new HufTree(i,cont[i]));
    int i=0;
    while(!pq.empty()&&pq.size()>1)
    {
        HufTree* min1=pq.top();
        pq.pop();
        HufTree* min2=pq.top();
        pq.pop();
        HufTree* tem=new HufTree(' ',min1->weight+min2->weight);
        tem->left=min1;
        update0(tem->left);
        tem->right=min2;
        update1(tem->right);
        pq.push(tem);
    }
    HufTree*root=pq.top();
    levelTra(root);
    while(!out.empty())
    {
        HufTree* tem=out.top();
        cout<<tem->data<<" "<<tem->weight<<" "<<tem->code<<endl;
        out.pop();
    }
	return 0;
}

实在是不会写oj了没想到这种通篇动态数据结构还真能过

sicily Huffman Coding V1

也能勉强算Huffman树模板类了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值