标题:赫夫曼算法
取消只看楼主
zuibangde
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2008-12-7
 问题点数:0 回复次数:0 
赫夫曼算法
#include<iostream.h>
#define Max 21
typedef struct{
    char data;
    int weight;
    int parent;
    int left;
    int right;
}huffnode;
typedef struct{
    char cd[Max];
    int start;
}huffcode;
void main(){
    huffnode ht[2*Max];
    huffcode hcd[Max],d;
    int i,k,f,r,l,n,c,m1,m2;
    cout<<"元素个数:";
    cin>>n;
    for(i=1;i<=n;i++){
        cout<<"第"<<i<<"个元素=>\t节点值:";
        cin>>ht[i].data;
        cout<<"\t\t权 重:";
        cin>>ht[i].weight;
    }
    for(i=1;i<=2*n-1;i++)
        ht[i].parent=ht[i].left=ht[i].right=0;
    for(i=n+1;i<=2*n-1;i++){
        m1=m2=32767;
        l=r=0;
        for(k=1;k<=i-1;k++)
            if(ht[k].parent==0)
                if(ht[k].weight<m1){
                    m2=m1;
                    r=l;
                    m1=ht[k].weight;
                    l=k;
                }
                else if(ht[k].weight<m2){
                    m2=ht[k].weight;
                    r=k;
                }
                ht[l].parent=i;
                ht[r].parent=i;
                ht[i].weight=ht[l].weight+ht[r].weight;
                ht[i].left=l;
                ht[i].right=r;
    }
    for(i=1;i<=n;i++){
        d.start=n+1;
        c=i;
        f=ht[i].parent;
        while(f!=0){
            if(ht[f].left==c)
                d.cd[--d.start]='0';
            else
                d.cd[--d.start]='1';
            c=f;
            f=ht[f].parent;
        }
        hcd[i]=d;
    }
    cout<<"输入赫夫曼编码:\n";
    for(i=1;i<=n;i++){
        cout<<"  "<<ht[i].data<<":";
        for(k=hcd[i].start;k<=n;k++)
            cout<<hcd[i].cd[k];
        cout<<endl;
    }
}
搜索更多相关主题的帖子: 赫夫曼 
2008-12-07 18:32



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-248167-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.091867 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved