哈夫曼樹之哈夫曼編碼分析-算法設計與分析報告C/C++版

設計如圖所示

 

 

 

有點長了,如果看着不舒服的話,就下載下來pdf文檔吧

代碼如下

//author:rgh
#pragma warning
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <map>
using namespace std; 
#define MAX 101
int n;
struct HTreeNode				//哈夫曼樹結點類型
{
	char data;					//字符
	int weight;					//權值
	int parent;					//雙親的位置
	int lchild;					//左孩子的位置
	int rchild;					//右孩子的位置
};
HTreeNode ht[MAX];				//哈夫曼樹
map<char,string> htcode;			//哈夫曼編碼

struct NodeType		//優先隊列結點類型
{
	int no;				//對應哈夫曼樹ht中的位置
	char data;			//字符
	int  weight;		//權值
	bool operator<(const NodeType &s) const
	{					//用於創建小根堆
		return s.weight<weight;
	}
};
void CreateHTree()						//構造哈夫曼樹
{
	NodeType e,e1,e2;
	priority_queue<NodeType> qu;
	for (int k=0;k<2*n-1;k++)	//設置所有結點的指針域
		ht[k].lchild=ht[k].rchild=ht[k].parent=-1;
	for (int i=0;i<n;i++)				//將n個結點進隊qu
	{
		e.no=i;
		e.data=ht[i].data;
		e.weight=ht[i].weight;
		qu.push(e);
	}
	for (int j=n;j<2*n-1;j++)			//構造哈夫曼樹的n-1個非葉結點
	{
		e1=qu.top();  qu.pop();		//出隊權值最小的結點e1
		e2=qu.top();  qu.pop();		//出隊權值次小的結點e2
		ht[j].weight=e1.weight+e2.weight; //構造哈夫曼樹的非葉結點j	
		ht[j].lchild=e1.no;
		ht[j].rchild=e2.no;
		ht[e1.no].parent=j;			//修改e1.no的雙親爲結點j
		ht[e2.no].parent=j;			//修改e2.no的雙親爲結點j
		e.no=j;						//構造隊列結點e
		e.weight=e1.weight+e2.weight;
		qu.push(e);
	}
}
void CreateHCode()			//構造哈夫曼編碼
{
	string code;
	code.reserve(MAX);
	for (int i=0;i<n;i++)	//構造葉結點i的哈夫曼編碼
	{
		code="";
		int curno=i;
		int f=ht[curno].parent;
		while (f!=-1)				//循環到根結點
		{
			if (ht[f].lchild==curno)	//curno爲雙親f的左孩子
				code='0'+code;
			else					//curno爲雙親f的右孩子
				code='1'+code;
			curno=f; f=ht[curno].parent;
		}
		htcode[ht[i].data]=code;	//得到ht[i].data字符的哈夫曼編碼
	}
}
void DispHCode()					//輸出哈夫曼編碼
{
	map<char,string>::iterator it;
	for (it=htcode.begin();it!=htcode.end();++it)
		cout << "    " << it->first << ": " << it->second <<	endl;
}
void DispHTree()					//輸出哈夫曼樹
{
	for (int i=0;i<2*n-1;i++)
	{
		printf("    data=%c, weight=%d, lchild=%d, rchild=%d, parent=%d\n",
			ht[i].data,ht[i].weight,ht[i].lchild,ht[i].rchild,ht[i].parent);
	}
}
int WPL()				//求WPL
{
	int wps=0;
	for (int i=0;i<n;i++)
		wps+=ht[i].weight*htcode[ht[i].data].size();
	return wps;
}

int main()
{
	n=5;
	ht[0].data='a'; ht[0].weight=4;		//置初值即n個葉子結點
	ht[1].data='b'; ht[1].weight=2;  
	ht[2].data='c'; ht[2].weight=1;  
	ht[3].data='d'; ht[3].weight=7;  
	ht[4].data='e'; ht[4].weight=3;  
	CreateHTree();					//建立哈夫曼樹
	printf("構造的哈夫曼樹:\n");
	DispHTree();
	CreateHCode();					//求哈夫曼編碼
	printf("產生的哈夫曼編碼如下:\n");
	DispHCode();					//輸出哈夫曼編碼
	printf("WPL=%d\n",WPL());
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章