哈弗曼编码

#include "stdafx.h"
#include <math.h>
#include <string>
#include <iostream>
using namespace std;
#define N 5
#define M 2*N-1
#define  MAXINT 100
struct Node
{
	int weight;
	int parent;
	int LChild;
	int RChild;
}HuffmanTree[M+1];
char *HuffmanCode[N+1];
int weight[N+1]={0,5,7,3,4,8};

void SelectMin(struct Node *T, int k, int *p1, int *p2)
{ 
	if(k < 2)  return ; 
    int small1 = MAXINT; 
    int small2 = MAXINT; 
    int i; 
    for(i=1; i<=k; i++) 
	{ 
		if(T[i].parent == 0) 
		{  
			if(T[i].weight < small1) 
			{     				
				small2 = small1;
				small1 = T[i].weight; 
				*p2 = *p1;    
				*p1 = i;  
			} else if(T[i].weight < small2) 
				{      
					small2 = T[i].weight;  
					*p2 = i;  
				}   
		}  
    }    	
}

//从无父节点的节点中取两个最小的
void CrtHuffmanTree(struct Node ht[],int m,int w[],int n)
{
	int s1,s2;
	int i;
	for(i=1;i<=n;i++)
	{
		ht[i].weight = w[i];
		ht[i].parent = 0;
		ht[i].LChild = 0;
		ht[i].RChild = 0;
	}
	for(i=n+1;i<=m;i++)
	{
		ht[i].weight = w[i];
		ht[i].parent = 0;
		ht[i].LChild = 0;
		ht[i].RChild = 0;
	}
	for(i=n+1;i<=m;i++)
	{
		SelectMin(ht,i-1,&s1,&s2);
		ht[i].weight = ht[s1].weight+ht[s2].weight;
		ht[s1].parent = i;
		ht[s2].parent = i;
		ht[i].LChild = s1;
		ht[i].RChild = s2;
	}
}

//从根节点开始 左子树为0右子树为1
void CrtHuffmanCode(struct Node ht[],char *hc[],int n)
{
	int start,c,p;
	char *cd;
	cd = (char *)malloc((n+1)*sizeof(char));
	cd[n-1] = '\0';
    for(int i=1;i<=n;i++)
	{
		start = n-1;
		c= i;
		p =ht[i].parent;
		while(p!=0)
		{
			--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);
}

int main(int argc, char* argv[])
{
	int i;
	CrtHuffmanTree(HuffmanTree,M,weight,N);
	CrtHuffmanCode(HuffmanTree,HuffmanCode,N);
	for(i=1;i<=M;i++)
		cout<<HuffmanTree[i].weight<<" "<<HuffmanTree[i].parent<<" "<<HuffmanTree[i].LChild<<" "<<HuffmanTree[i].RChild<<endl;
	for(i=1;i<=N;i++)
		cout<<HuffmanCode[i]<<endl;
	return 0;
}

 

posted on 2014-11-13 13:26  kangbry  阅读(134)  评论(0编辑  收藏  举报

导航