对字符串HELL0_HULU中的字符进行二进制编码,使得字符串的编码长度尽可能短,最短长度为?

来源:互联网 发布:数据库开发与dba 编辑:程序博客网 时间:2024/05/18 13:42

这个题主要考察的是对haffman树的解法。先给出代码,因为其中还有点小错误,但是影响不大。

#include <stdio.h>#include<string.h>#include<stdlib.h>typedef struct HuffmanNode{unsigned int weight;int parent,lchild,rchild;}HuffmanNode,*HuffmanTree;typedef char ** HuffmanCode;char *count(char *input,int *temp){//统计单个字母出现的顺序int i;int len=strlen(input);int hash[256]={0};int count=0;for(i=0;i<len;i++){hash[input[i]]++;}for(i=0;i<256;i++)//统计出现的字符个数{if(hash[i])count++;}char *output=(char*)malloc(count+1);count=0;for(i=0;i<256;i++) //存储出现的字符{if(hash[i]!=0){output[count++]=i;*temp=hash[i];temp++;}}output[count]='\0';return output;}int min(HuffmanTree *HT,int n){//找到其中最小的一个int i=0;unsigned int k=1000;int flag;while((*HT)[i].parent!=0)i++;for(;i<=n;i++)if((*HT)[i].parent==0&&(*HT)[i].weight<k){k=(*HT)[i].weight;flag=i;}(*HT)[flag].parent=1;return flag;}void select(HuffmanTree *HT,int i,int *s1,int *s2){//找到权值最小的两个元素的下标*s1=min(HT,i);*s2=min(HT,i);if((*s1)>(*s2)){int temp=*s1;*s1=*s2;*s2=temp;}}void get_huffman_code(HuffmanTree *HT,HuffmanCode *HC,int n,int *w){int m;int s1,s2;int i;int c,f;m=2*n-1;*HT=(HuffmanNode*)malloc(sizeof(HuffmanNode)*(m+1));HuffmanNode *p;p=*HT+1;for(i=1;i<=n;i++){p->weight=*w;p->parent=0;p->lchild=0;p->rchild=0;w++;p++;}for(;i<=m;i++){p->weight=0;p->parent=0;p->lchild=0;p->rchild=0;p++;}for(i=n+1;i<=m;i++){select(HT,i-1,&s1,&s2);(*HT)[i].weight=(*HT)[s1].weight+(*HT)[s2].weight;(*HT)[i].lchild=s1;(*HT)[i].rchild=s2;(*HT)[s1].parent=(*HT)[s2].parent=i;}*HC=(char**)malloc(sizeof(char*)*(n+1));char *temp=(char*)malloc(sizeof(n));int start;temp[n-1]='\0';for(i=1;i<=n;i++){start=n-1;for(c=i,f=(*HT)[i].parent;f!=0;c=f,f=(*HT)[f].parent){if((*HT)[f].lchild==c)temp[--start]='0';else if((*HT)[f].rchild==c)temp[--start]='1';}(*HC)[i]=(char*)malloc(sizeof(n-start));strcpy((*HC)[i],temp+start);}}void main(){int hash[256]={0};char string[]="hello_hulu";char *p=count(string,hash);printf("%s\n",p);HuffmanTree HT;HuffmanCode HC;int n=strlen(p);get_huffman_code(&HT,&HC,n,hash);for(int i=1;i<=n;i++)  int length=0;for(i=0;i<n;i++)length+=strlen(HC[i+1])*hash[i];printf("%d\n",length);}

运行结果如图:




原创粉丝点击