ハフマンツリーの構築とコードC言語


ハフマンツリーの構築と符号化

#include
#include
#define N 20
#define M 2*N-1

typedef struct{
     
	int weight;  // 
	int parent;  // 
	int lchild;   // 
	int rchild;   // 
}huffmantree;

typedef struct{
     
	int start;  
	char codes[N];   // 
}huffmancode;

void creathuffman(huffmantree tree[],int n){
     
	int i,j,w,p1,p2,small1,small2;
	int m = 2*n;
	for (i=1;i<m;i++){
           // 
		tree[i].weight = 0;
		tree[i].lchild = 0;
		tree[i].rchild = 0;
		tree[i].parent = 0;
	}
	printf("input weight:");
	for (i=1;i<=n;i++){
         // 
	    scanf("%d",&w);
		tree[i].weight = w;	
	}
	for(i=1;i<m;i++){
     
		printf("%d  %d  %d  %d
"
,tree[i].weight,tree[i].parent,tree[i].lchild,tree[i].rchild); } for(i=n+1;i<m;i++) // { p1=0; p2=0; small1 = 10000; small2 = 10000; for(j=1;j<i;j++) { if(tree[j].parent==0) { if(tree[j].weight<small1) { small2 = small1; small1 = tree[j].weight; p2 = p1; p1 = j; } else if(tree[j].weight<small2) { small2 = tree[j].weight; p2 = j; } } } tree[i].weight = (tree[p1].weight+tree[p2].weight); tree[i].lchild = p1; tree[i].rchild = p2; tree[p1].parent = i; tree[p2].parent = i; } } void codehuffman(huffmantree *tree,huffmancode *code,int n){ huffmancode temp; int i,c,p; for(i=1;i<=n;i++){ temp.start = n; c = i; p = tree[i].parent; while(p!=0){ --temp.start; if (tree[p].lchild == c) temp.codes[temp.start] = '0'; else temp.codes[temp.start] = '1'; c = p; p = tree[p].parent; } code[i] = temp; } } void main(){ int n,i,j; huffmantree tree[M]; huffmancode code[N]; printf("input str nums:"); scanf("%d",&n); creathuffman(tree,n); codehuffman(tree,code,n); for(i=1;i<=(2*n)-1;i++) printf("%d %d %d %d
"
,tree[i].weight,tree[i].parent,tree[i].lchild,tree[i].rchild); for(i=1;i<=n;i++){ for(j=code[i].start;j<=n;j++) { printf("%c",code[i].codes[j]); }putchar('
'
); } }