////////////// 主要操作的是下标 #if 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include<windows.h> #define Max 32767 typedef char* HuffMan; typedef struct Node { int weight; int parent; int lchild,rchild; }htnode,*HuffManTree; void Select(HuffManTree *HT,int n,int *s1,int *s2) { int i; int min_weight=Max; if(n<1) { printf("n的范围不对!结束"); exit(-1); } for(i=1;i<=n;i++) { if((*HT)[i].parent==0) { if((*HT)[i].weight<min_weight) { min_weight=(*HT)[i].weight; *s1=i; } } } (*HT)[*s1].parent=1; //标记s1已经被查询过 min_weight=Max; for(i=1;i<=n;i++) { if((*HT)[i].parent==0) { if((*HT)[i].weight<min_weight) { min_weight=(*HT)[i].weight; *s2=i; } } } (*HT)[*s2].parent=1; //标记s2已经被查询过 } void HuffManCoding(HuffManTree *HT,int *w,int n) { int i; int s1,s2; int m=2*n-1; *HT=(HuffManTree)malloc((m+1)*sizeof(htnode)); if(NULL==HT) { printf("开辟空间失败"); exit(-1); } for(i=1;i<=n;i++) { (*HT)[i].weight=*w; (*HT)[i].parent=0; (*HT)[i].lchild=0; (*HT)[i].rchild=0; w++; } for(i=n+1;i<=m;i++) { (*HT)[i].weight=0; (*HT)[i].parent=0; (*HT)[i].lchild=0; (*HT)[i].rchild=0; } for(i=n+1;i<=m;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; } } void HuffManInput(HuffManTree *HT,HuffMan* HC,int n) { int start; int c,f,i; char* cd=(char*)malloc(n*sizeof(char)); if(NULL==cd) exit(-1); HC=(HuffMan*)malloc((n+1)*sizeof(char*)); if(NULL==HC) exit(-1); cd[n-1]='\0'; for(i=1;i<=n;i++) { start=n-1; f=(*HT)[i].parent; for(c=i;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)); if(NULL==HC[i]) exit(-1); strcpy(HC[i],&cd[start]); } free(cd); printf("输出赫夫曼编码\n"); for(i=1;i<=n;i++) { printf("%d:%s\n",(*HT)[i].weight,HC[i]); } } void main() { int i=0; int number=0; int *w=NULL; HuffManTree HT=NULL; HuffMan HC=NULL; printf("请输入待编码字符的个数:\n"); scanf("%d",&number); w=(int *)malloc(number*sizeof(int)); if(!w) exit(-1); printf("请输入整形待权值\n"); for(i=0;i<number;i++) { scanf("%d",&w[i]); } HuffManCoding(&HT,w,number); HuffManInput(&HT,&HC,number); /* for(i=1;i<=n;i++) { printf("%s\n",HC[i]); }*/ system("pause"); system("cls"); } #endif