请高手帮忙看一下,实在是找不错哪里有问题!
humin
2007-06-12
为什么编码输出不正确啊?
#include<iostream> #include<cstring> #include<cstdlib> using namespace std; typedef struct { unsigned int weight; unsigned int parent,lchild,rchild; } HTNode,*HuffmanTree; typedef char * * Huffmancode; void Huffmancoding( HuffmanTree &HT, Huffmancode &HC,int *w,int n) { int i,m,S1,S2;int small1,small2; small1=small2=32767; S1=S2=0; HTNode *p=0; 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) { (*p).weight=*w; (*p).parent=0; (*p).rchild=0; (*p).rchild=0; } for(;i<=m;++i,++p) { (*p).lchild=0; (*p).parent=0; (*p).rchild=0; (*p).weight=0; } for(i=n+1;i<=m;++i) { { for (int j=1;j<=i-1;++j) if(HT[j].parent==0) { if(HT[j].weight<small1) { small2=small1; S2=S1; small1=HT[j].weight; S1=j; } else if(HT[j].weight<small2) { small2=HT[j].weight; S2=j; } } } 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-1]='\0'; for(i=1;i<=n;++i) { int start=n-1; for(int 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); } int main() { int A[]={1,2,4,9}; HuffmanTree HT; Huffmancode HC; Huffmancoding( HT, HC,A,4); for(int i=1;i<=4;++i) { for(int j=0;HC[i][j]!='\0';++j) cout<<HC[i][j]; cout<<endl; } //cout<<HC[i]<<endl; return 0; } |
|
humin
2007-06-13
谢谢,已经解决!
|