Huffman树的利用:
1、先选择1篇文章
2、然后统计字符个数
3、对个数不为0字符的进行编码
4、输出码文
5、进行译码
上机代码:
/*************************************************************************
> File Name: Huffman树的利用.cpp
> Author: zzuspy
> Mail: zzuspy@qq.com
> Created Time: 2014年12月3日 14:30
************************************************************************/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <queue>
#define LL long long
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,c) min(a,min(b,c))
using namespace std;
typedef struct
{
int weight;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char * * HuffmanCode;
int s1,s2;
void Select(HuffmanTree &HT,int n)
{
int i,min;
for(int i=1; i<=n; i++)
{
if(HT[i].parent==0)
{
min = i;
break;
}
}
for(i=1; i<=n; i++)
{
if(HT[i].weight<HT[min].weight && HT[i].parent == 0)min = i;
}
s1 = min;
for(int i=1; i<=n; i++)
{
if(HT[i].parent==0 && i!=s1)
{
min = i;
break;
}
}
for(int i=1; i<=n; i++)
{
if(HT[i].parent == 0 && i!=s1 && HT[i].weight<HT[min].weight && HT[i].weight>=HT[s1].weight) min=i;
}
s2 = min;
}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n)
{
if(n<=1) return;
int m = 2 * n - 1,i;
HuffmanTree p;
HT = (HuffmanTree)malloc( (m + 1) * sizeof(HTNode));
for( p = HT+1,i = 1; i <= n; i++,p++,w++)
{
p->weight = *w;
p->parent = p->lchild = p->rchild = 0;
}
for(; i <= m; i++,p++)
{
p->weight = p->parent = p->lchild = p->rchild = 0;
}
//输出这时候Huffman树
/*for(int i=1; i<=n; i++)
{
printf(%d %d %d %d
,HT[i].weight,HT[i].parent,HT[i].lchild,HT[i].rchild);
}*/
for(i = n + 1; i<=m; i++)
{
Select(HT,i⑴);
//printf(%d %d
,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 *));
char *cd = (char *)malloc( n * sizeof(char) );
cd[n⑴] = '