哈夫曼树编/译码算法

一、实验目的:

掌握哈弗曼编/译码算法。

1. 掌握Huffman 树的概念、特点和存储结构;

2. 掌握Huffman 树的构造方法;

3. 学会灵活运用Huffman 树解决编码问题。

4. 【问题描述】

5.  某报文中共出现n个字符,各字符出现频度依次为w1,w2,…,wn。要求设计一个不等长的编码方案,输出每个字符对应的编码,使得该编码系统的空间效率最好。

6. 要求字符个数和相应的权值要从终端输入。

在前面的基础上,实现哈弗曼译码算法,对给定的一组编码(要求从终端输入),译出其对应的报文部分

#include 
using namespace std;
//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define maxsize 100
//OVERFLOW 在 math.h 中已定义为3
typedef int Status;
typedef int Boolean; // 布尔类型
typedef struct{
    char ch;
    unsigned int weight;
    unsigned int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char * *HuffmanCode;


int min1(HuffmanTree &t,int i)
{
    int j,flag;
    unsigned int k = UINT_MAX;
    for (j = 1;j <= i;j++)
        if(t[j].weight < k && t[j].parent == 0)
            k = t[j].weight,flag = j;
            t[flag].parent = 1;
            return flag;
}
void Select(HuffmanTree &t,int i,int &s1,int &s2)
{
    int j;
    s1 = min1(t,i);
    s2 = min1(t,i);
    if(t[s1].weight > t[s2].weight)
    {
        j = s1;
        s1 = s2;
        s2 = j;
    }
}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,char *ch,int *w,int n)
{
    int i,m,s1,s2,start;
    unsigned int c,f;
    HuffmanTree p;
    char *cd;
    if (n <= 1)
        return;
    m = 2 * n - 1;
    HT = (HuffmanTree)malloc((m+1)*sizeof(HTNode));
    for(p = HT+1,i = 1;i <= n;++i,++p,++w,++ch)
    {
        p -> ch = *ch;
        p -> weight = *w;
        p -> parent = 0;
        p -> lchild = 0;
        p -> rchild = 0;
    }
    for(;i <= m;++i,++p)
    {
        p -> ch = '0';
        p -> weight = 0;
        p -> parent = 0;
        p -> lchild = 0;
        p -> rchild = 0;
    }
    for(i = n+1;i <= m;++i)
    {
        Select(HT,i-1,s1,s2);
        HT[s1].parent = i;
        HT[s2].parent = i;
        HT[i].lchild = s1;
        HT[i].rchild = s2;
        HT[i].weight = HT[s1].weight + HT[s2].weight;
    }
    HC = (HuffmanCode)malloc((n+1)*sizeof(char*));
    cd = (char*)malloc(n*sizeof(char));
    cd[n-1] = '\0';
    for(i = 1;i <=n;++i)
    {
        start = n-1;
        for(c = i,f = HT[i].parent;f !=0;c =f,f = HT[f].parent)
            if(HT[f].lchild == c)
            cd[--start] = '0';
        else
            cd[--start] = '1';
        HC[i] = (char * )malloc((n-start)*sizeof(char));
        strcpy(HC[i],&cd[start]);

    }
    free(cd);
}
void HuffmanTranslate(HuffmanTree &HT,int n)
{
    int i,j = 0,k = 0,flag = 0;
    char c[maxsize] = "\0";
    char b[maxsize];
    char endflag = '5';
    i = 2 * n - 1;
    cout <<"请输入译码:"<> n;
    int *w = (int*)malloc(n*sizeof(int));
    char *c = (char *)malloc(n*sizeof(char));
    cout <<"请输入"<

哈夫曼树编/译码算法_第1张图片

你可能感兴趣的:(数据结构)