#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 10 // 带编码字符的个数,即树中叶结点的最大个数
#define M (2*N-1) // 树中总的结点数目
class HTNode{ // 树中结点的结构
public:
char data;
int weight;
int parent,lchild,rchild;
};
class HTCode{
public:
char data; // 待编码的字符
int weight; // 字符的权值
char code[N];
int start; // 字符的编码
};
void Init(HTCode hc[], int *n){
// 初始化,读入待编码字符的个数n,从键盘输入n个字符和n个权值
int i;
cout<<"输入字符个数:";
cin>>*n;
cout<<"输入"<<*n<<"个字符";
for(i=1; i<=*n; ++i)
cin>>hc[i].data;
cout<<"输入"<<*n<<"个权值";
for(i=1; i<=*n; ++i)
cin>>hc[i].weight;
}
void Select(HTNode ht[], int k, int *s1, int *s2){
// ht[1...k]中选择parent为0,并且weight最小的两个结点,其序号由指针变量s1,s2指示
int i;
for(i=1; i<=k && ht[i].parent != 0; i++){}
*s1 = i;
for(i=1; i<=k; ++i){
if(ht[i].parent==0 && ht[i].weight<ht[*s1].weight)
*s1 = i;
}
for(i=1; i<=k; i++){
if(ht[i].parent==0 && i!=*s1)
break;
}
*s2 = i;
for(i=1; i<=k; i++){
if(ht[i].parent==0 && i!=*s1 && ht[i].weight<ht[*s2].weight)
*s2 = i;
}
}
void print(HTNode ht[],int k ,int n)
{
if(k==0)
{
return;
}
for (int i=0;i<n;i++)
{
cout<<" ";
}
if(ht[k].parent!=-1)
{
cout<<"|_";
}
else {
cout<<" ";
}
cout<<ht[k].data<<endl;
int L=ht[k].lchild;
int R=ht[k].rchild;
print(ht,R,n+2);
print(ht,L,n+2);
}
void HuffmanCoding(HTNode ht[],HTCode hc[],int n){
// 构造Huffman树ht,并求出n个字符的编码
char cd[N];
HTCode d;
int i,j,m,c,f,s1,s2,start;
for(i=1; i<=2*n-1; i++)
{
if(i <= n)
ht[i].weight = hc[i].weight;
else
ht[i].parent = 0;
ht[i].parent = ht[i].lchild = ht[i].rchild = 0;
}
for(i=n+1; i<=2*n-1; 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;
} cd[n-1] = '\0';
for(i=1; i<=n; i++){
start = n-1;
for(c=i,f=ht[i].parent; f; c=f,f=ht[f].parent){
if(ht[f].lchild == c)
cd[--start] = '0';
else
cd[--start] = '1';
}
strcpy(hc[i].code, &cd[start]);
}
}
void enCoding(HTNode ht[],HTCode hc[],int n)
{
int q,k;
char bs;
cout<<"请输入字符代码: "<<endl;
cin>>bs;
for(q=0;bs!=10;q++)
{
bs=getchar();
for(int i=1;i<=n;i++)
{
if (bs==hc[i].data)
for(k=hc[i].data;k<=n;k++)
cout<<hc[i].code[k];
}
}
cout<<endl;
int t,u;
char c[100];
t=2*n-1;
cout<<"\n请输入哈夫曼码: "<<endl;
cin>>c;
for(u=0;c[u]!='\0';u++)
{
if(c[u]=='0')
{
t=ht[t].lchild;
}
else if(c[u]=='1')
{
t=ht[t].rchild;
}
if(t<n+1)
{
cout<<ht[t].data;
t=2*n-1;
}
}cout<<endl;
}
int main(int i, int n )
{
int m,w[N+1];
HTNode ht[M+1];
HTCode hc[N+1];
Init(hc, &n); // 初始化
HuffmanCoding(ht,hc,n); // 构造Huffman树,并形成字符的编码
for(i=1; i<=n; i++)
cout<<hc[i].data<<"---"<<hc[i].code<<endl;
print(ht, 2*n-1, 0);
enCoding(ht,hc,n);
cout<<endl;
return 0;
}
void enCoding()函数中输入字符后,cout<<hc[i].code[k];为什么没有输出啊,我把他换成了cout<<"-------------";测试了一下也没有输出”------------“这个,这是怎么回事啊???请大家帮忙
你的main函数定义有错误吧?没见过你这样用的。常规用法:
int main( int argc, char *argv[])
你百度一下。
你在用哈夫曼树压缩吗,正好我最近也在做这个。。。
至于你这个问题。。。如果按照你说的的话应该是没有进入循环。
个人感觉是hc[i].data是char 类型,所以对应的ASCII码大于了n。