#include
#include
#include
#define M 2*N-1
#define ch 30
#define NUM 100
#define N 6
typedef char numcode[NUM];
typedef char charcode[ch];
typedef char* HuffmanCode[N] ;
typedef struct{
int weight;
int parent;
int lchild;
int rchild;
}HTNode,HuffmanTree[M];
void select(HuffmanTree ht,int pos,int *t1,int *t2){
int j,s2;
int s1=66666;
for(j=0;j<=pos;j++) {
if(ht[j].weight
s2=s1;*t2=*t1;
*t1=j;s1=ht[j].weight;
}
}
else if(ht[j].weight
s2=ht[j].weight;
*t2=j;
}
}
}
}
void CrtHuffmanTree(HuffmanTree ht,int w[],int n){
int i,t1,t2,m;
m=2*n-1;
for(i=0;i
ht[i].lchild=-1;ht[i].rchild=-1;
}
for(i=n;i
ht[i].lchild=-1;ht[i].rchild=-1;
}
for(i=n;i
ht[i].weight=ht[t1].weight+ht[t2].weight;
ht[t1].parent=i;
ht[t2].parent=i;
ht[i].lchild=t1;
ht[i].rchild=t2;
}
}
void CrtHuffmanCode(HuffmanTree ht,HuffmanCode hc,int n){
char *cd;int start,c,p,i;
cd=(char*)malloc(n*sizeof(char));
cd[n-1]='\0';
for(i=0;i
p=ht[i].parent;
while(p!=-1){
--start;
if(ht[p].lchild==c) cd[start]='0';
else cd[start]='1';
c=p;p=ht[p].parent;
}
hc[i]=(char*)malloc((n-start)*sizeof(char));
strcpy(hc[i],&cd[start]);
}
free(cd);
}
void printcode(char s[],HuffmanCode hc){
int i;
for(i=0;i
printf("%s\n",hc[i]);
}
}
void chartocode(charcode c,char s[],HuffmanCode hc){
char *p=c;
int j;
while(*p!='\0'){
for(j=0;j
printf("%s",hc[j]);
}
p++;
}
printf("\n");
}
void numtochar(numcode ns,HuffmanTree ht,char s[]){
char *p=ns;int key;HTNode g;
while(*p!='\0'){
g=ht[M-1];
while(g.lchild!=-1&&g.rchild!=-1&&(*p!='\0')){
switch(*p){
case '0':key=g.lchild;g=ht[g.lchild];break;
case '1':key=g.rchild;g=ht[g.rchild];break;
}
p++;
}
printf("%c",s[key]);
}
}
int main(){
HuffmanTree ht;HuffmanCode hc;charcode c;numcode ns;
char s[N]={'A','B','C','D','E','F'};
int w[N],i;
for(i=0;i
}
scanf("%s",&c);
scanf("%s",&ns);
CrtHuffmanTree(ht,w,6);
CrtHuffmanCode(ht,hc,6);
printcode(s,hc);
chartocode(c,s,hc);
numtochar(ns,ht,s);
}