#include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include<functional>
#include <vector>
#include <map>
using namespace std;
const int INF=70;
char record[INF];
int weight[INF];
map<char,string>mp;
class NodeTree //存储节点信息
{
public:
NodeTree(char s='#',int w=-1):str(s),weight(w) //构造函数
{
lchild=NULL; rchild=NULL;
}
bool LessThan(const NodeTree* temp)const //比较函数
{
if(weight!=temp->weight)
return weight>temp->weight;
else
return str>temp->str;
}
char GetStr(){return str;}
int GetWeight(){return weight;}
char GetBinary(){return binary;}
NodeTree* Getlchild(){return lchild;}
NodeTree* Getrchild(){return rchild;}
void SetBinary(char s){binary=s;}
void SetWeight(int s){weight=s;}
void Setlchild(NodeTree *node){lchild=node;}
void Setrchild(NodeTree *node){rchild=node;}
private:
char str; //记录字符
int weight; //记录权值
char binary; //记录在哈夫曼树上的编码
NodeTree *lchild,*rchild; //记录该节点的左右孩子节点
friend class Compare;
};
class Compare
{
public:
bool operator()(const NodeTree* temp1,const NodeTree* temp2)
{
return temp1->LessThan(temp2);
}
};
void Input(int n) //输入处理
{
for(int i=0;i<n;i++)
{
getchar();
scanf("%c%*c%d",&record[i],&weight[i]);
}
}
NodeTree* CreateHaffmanTree(int n) //构造哈夫曼树
{
priority_queue<NodeTree*,vector<NodeTree*>,Compare>nodetree;
for(int i=0;i<n;i++) //存储信息
{
NodeTree *temp=new NodeTree(record[i],weight[i]);
nodetree.push(temp);
}
while(nodetree.size()>1)
{//cout<<" hello"<<endl;
NodeTree *temp1=nodetree.top();
nodetree.pop();
NodeTree *temp2=nodetree.top();
nodetree.pop();
NodeTree *temp=new NodeTree();
temp->SetWeight(temp1->GetWeight()+temp2->GetWeight());
temp1->SetBinary('0'); temp2->SetBinary('1');
temp->Setlchild(temp1); temp->Setrchild(temp2);
nodetree.push(temp);
}
return nodetree.top();
}
void dfs(char temp[INF],NodeTree* np,int cnt) //确定编码
{
if(np->Getlchild()==NULL && np->Getrchild()==NULL)
{
temp[cnt-1]=np->GetBinary();
temp[cnt]='\0';
string t(temp);
mp[np->GetStr()]=t;
return;
}
if(cnt) temp[cnt-1]=np->GetBinary();
dfs(temp,np->Getlchild(),cnt+1);
dfs(temp,np->Getrchild(),cnt+1);
}
void Output(int n) //输出处理
{
for(int i=0;i<n;i++)
{
printf("%c:",record[i]);
cout<<mp[record[i]]<<endl;
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
Input(n);
NodeTree *root=CreateHaffmanTree(n);
char temp[INF];
dfs(temp,root,0);
Output(n);
}
return 0;
}
哈夫曼编码(备忘)
最新推荐文章于 2023-12-24 18:35:29 发布