#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,rchild;
};
HTreeNode ht[MAX];
map<char,string> htcode;
struct NodeType{
int no;
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++){
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++){
e1=qu.top();qu.pop();
e2=qu.top();qu.pop();
ht[j].weight=e1.weight+e2.weight;
ht[j].lchild=e1.no;
ht[j].rchild=e2.no;
ht[e1.no].parent=j;
ht[e2.no].parent=j;
e.no=j;
e.weight=e1.weight+e2.weight;
qu.push(e);
}
}
void CreateHCnode(){
string code;
code.reserve(MAX);
for(int i=0;i<n;i++){
code="";
int curno=i;
int f=ht[curno].parent;
while(f!=-1){
if(ht[f].lchild==curno) code='0'+code;
else code='1'+code;
}
htcode[ht[i].data]=code;
}
}
void DispHCnode(){
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",
ht[i].data,ht[i].weight,ht[i].lchild,ht[i].rchild,ht[i].parent);
}
}
int WPL(){
int wps=0;
for(int i=0;i<n;i++){
wps+=ht[i].weight*htcode[ht[i].data].size();
}
}
int main(){
n=5;
ht[0].data='a';ht[0].weight=4;
ht[0].data='a';ht[0].weight=4;
ht[0].data='a';ht[0].weight=4;
ht[0].data='a';ht[0].weight=4;
ht[0].data='a';ht[0].weight=4;
CreateHTree();
DispHTree();
CreateHCnode();
DispHCnode();
}
贪心法求解哈夫曼编码问题
最新推荐文章于 2021-11-18 11:25:53 发布