霍夫曼编码数据结构实验

#include<stdlib.h>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<assert.h>
#include<string>
using namespace std;

#define MAXNODE	100
#define MAXINT 0x7fffffff

struct HtNode		/* 哈夫曼树结点的结构 */
{
	int weight;
	int parent, lchild, rchild;
};

struct HtTree
{
    HtNode  ht[MAXNODE];
 	int    root; 	/* 哈夫曼树根在数组中的位置 */
}HtTree;

typedef struct HtTree *PHtTree;
typedef char** HuffmanCode;

void Select (PHtTree pht, int pos, int *x1, int *x2)
{    int  m1 = MAXINT, m2 = MAXINT; int j;
      /* 相关变量赋初值 */
      for (j=1; j<pos; j++)	/* 找两个最小权的无父结点的结点 */
      {
        if (pht->ht[j].weight<m1 && pht->ht[j].parent == 0)
            { 	m2 = m1;	*x2 = *x1;
                m1 = pht->ht[j].weight;
                *x1 = j;
            }
        else if (pht->ht[j].weight<m2 && pht->ht[j].parent == 0)
            {	m2 = pht->ht[j].weight;
                *x2 = j;
            }
      }
}

int main()
{
    freopen("in.txt","r",stdin);
    int n;cin>>n;
    char char_set[100];
    for(int i = 0;i<n;i++){
        cin>>char_set[i];
    }
    int w[100];
    for(int i = 1;i<=n;i++){
        cin>>w[i];
    }
    string packet;
    cin>>packet;
    PHtTree  pht;
	int  i, x1, x2;
  	pht = (PHtTree) malloc (sizeof (struct HtTree));
	/* 创建空哈夫曼树 */
  	assert(pht);
  	for( i=1; i<=2*n - 1; i++ )		/* 置初态 */
  	{ 	pht->ht[i].lchild = 0;
		pht->ht[i].rchild = 0;
		pht->ht[i].parent = 0;
		if (i<=n)  pht->ht[i].weight = w[i];
		else 	 pht->ht[i].weight = 0;
  	};
	/* 每循环一次构造一个内部结点 */
  	for( i=1; i < n ; i++ )
  	{
		Select (pht, n+i, &x1, &x2);
		pht->ht[x1].parent = n + i;	/* 构造一个内部结点 */
		pht->ht[x2].parent = n + i;
		pht->ht[n+i].weight = pht->ht[x1].weight
				        + pht->ht[x2].weight;
		pht->ht[n+i].lchild = x1;
		pht->ht[n+i].rchild = x2;
		pht->root = n+i;
  	}
  	HuffmanCode HC = (HuffmanCode)malloc((n+1)*sizeof(char*));
    char* cd=(char*) malloc (n*sizeof(char));
    cd[n-1]='\0';
    for (i=1; i<=n; ++i) {
        int start = n-1;
        for ( int c=i, f=pht->ht[i].parent; f!=0; c=f, f=pht->ht[f].parent){
            if (pht->ht[f].lchild == c) cd[--start]='0';
            else cd[--start]='1';
        }
        HC[i]=(char *) malloc ((n-start)*sizeof(char));
        strcpy (HC[i], &cd[start]);
    }
    for(int i = 0;i<packet.length();++i){
        for(int j = 1;j<=n;j++){
            if(packet[i]==char_set[j-1]){
                cout<<HC[j];
            }
        }
    }
    cout<<endl;
    cout<<packet;
    return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值