#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct cell{
struct cell* left;
struct cell* right;
int weight;
char info;
}tree;
int m=0;
void bubblesort(tree* p[],int n){
int i;
tree* tem;
for(i=n-1;i>1;i--){
for(int j=1;j<i;j++){
if(p[j]->weight>p[j+1]->weight){
tem=p[j];
p[j]=p[j+1];
p[j+1]=tem;
}
}
}
}
tree* Huffman(tree* h[],int m){
for(int i=1;i<=m;i++){
h[i]->left=NULL;
h[i]->right=NULL;
}
tree* t;
for(int i=1;i<m;i++){
t=(tree*)malloc(sizeof(tree));
t->weight=h[i]->weight+h[i+1]->weight;
t->info='\0';
t->left=h[i];
t->right=h[i+1];
int j=i+2;
while(t->weight>=h[j]->weight){
h[j-1]=h[j];
j=j+1;
}
h[j-1]=t;
}
return t;
}
void Huffmancode(tree* tmp,char info,int yy,int code[]){
if(tmp==NULL) return;
if(tmp->info==info){
m=yy;
return;
}
if(m==0){
code[yy]=0;
Huffmancode(tmp->left,info,yy+1,code);
}
if(m==0){
code[yy]=1;
Huffmancode(tmp->right,info,yy+1,code);
}
}
void decode(tree*p,char s[]){
char tool[5000];
int n=0;
int length=strlen(s);
tree*root=p;
int i;
for(i=0;i<length;i++){
if(s[i]=='0') root=root->left;
if(s[i]=='1') root=root->right;
if(root->left==NULL&&root->right==NULL){
tool[n]=root->info;
n++;
root=p;
}
if(root==NULL){
printf("INVALID");
return;
}
}
if(root->info=='\0'&&root!=p){
printf("INVALID");
return;
}
else{
for(int i=0;i<n;i++){
printf("%c",tool[i]);
}
}
}
int main(void){
char s[5000];
scanf("%s",s);
int length=strlen(s);
tree* p[5000];
tree* root;
int num=1;
for(int i=0;i<length;i++){
int flag=0;
for(int j=1;j<num;j++){
if(p[j]->info==s[i]){
p[j]->weight++;
flag=1;
break;
}
}
if(flag==0){
p[num]=new tree;
p[num]->weight=1;
p[num]->info=s[i];
p[num]->left=NULL;
p[num]->right=NULL;
num++;
}
}
p[num]=new tree;
tree* t[5000];
for(int i=1;i<num;i++){
t[i]=new tree;
t[i]->info=p[i]->info;
t[i]->weight=p[i]->weight;
t[i]->left=NULL;
t[i]->right=NULL;
}
// for(int i=1;i<num;i++){
// printf("%c:%d",p[i]->info,p[i]->weight);
//}
root=Huffman(p,num-1);
tree* root_1;
root_1=root;
printf("%d ",length);
int add=0;
for(int i=1;i<num;i++){
m=0;
int code[26];
Huffmancode(root,t[i]->info,0,code);
add=(add+m*t[i]->weight);
}
printf("%d\n",add/8+1);
for(int i=1;i<num;i++){
m=0;
int code[5000];
Huffmancode(root,t[i]->info,0,code);
printf("%c:",t[i]->info);
for(int j=0;j<m;j++){
printf("%d",code[j]);
}
printf("\n");
}
char aa[5000],bb[5000];
scanf("%s",aa);
getchar();
decode(root_1,aa);
scanf("%s",bb);
decode(root_1,bb);
}

你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答
本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。
因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。