#include<bits/stdc++.h>
using namespace std;
#define MAX 101
#define MaxWeight 300 //最大权值
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();
void CreateHCode();
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()
{
cin >> n;
for(int i=0;i<n;i++)
{
cin >> ht[i].data >> ht[i].weight;
}
CreateHTree(); //建立哈夫曼树
CreateHCode(); //求哈夫曼编码
printf("WPL=%d\n",WPL());
// for(int i=0;i<2*n-1;i++)
// cout<<htcode['A'+i]<<" ";
return 0;
}
/* 请在这里填写答案 */
void CreateHTree()
{
int i,j;
int x1,x2,w1,w2;
for(i=0;i<2*n-1;i++)
{
ht[i].parent=-1;
ht[i].lchild=-1;
ht[i].rchild=-1;
}
for(i=n;i<2*n-1;i++)
{
x1=x2=-1;
w1=w2=MaxWeight; //初始为最大权值
//寻找两个权值最小的结点
for(j=0;j<i;j++)
{
if(ht[j].parent==-1 && ht[j].weight<w1) //比最小权值小
{
w2=w1; x2=x1; //最小值变为次最小值
w1=ht[j].weight; x1=j; //更新最小值
}
else if(ht[j].parent==-1 && ht[j].weight<w2) //在最大和最小之间
{
w2=ht[j].weight; x2=j;
}
}
//连接结点,构造新树
ht[i].data='A'+i;
ht[i].lchild=x1; ht[i].rchild=x2;
ht[x1].parent=i; ht[x2].parent=i;
ht[i].weight=ht[x1].weight+ht[x2].weight;
}
// for(i=n;i<2*n-1;i++)
// cout<<"htparent="<<ht[i].parent<<" ";
// cout<<endl;
}
void CreateHCode()
{
int j=0,i,f,c,l=0;
// char a;
// cout<<"n="<<n<<endl;
for(i=0;i<n;i++)
{
l=0;
string cd(n,'\0'); //定义初始长度,便于使用下标访问
j=0;
c=i;
f=ht[i].parent;
while(f!=-1)
{
if(ht[f].lchild==c){
cd[j++]='0';l++;
}
else{
cd[j++]='1';l++;
}
c=f;
f=ht[f].parent;
}
cd.resize(l); //更新字符串长度
reverse(cd.begin(),cd.end()); //回溯构造编码,需置逆
cout<<cd<<endl;
//不使用库函数方法
// for(int k=0,j=l-1;k<j;k++,j--)
// {
// a=cd[k];
// cd[k]=cd[j];
// cd[j]=a;
// }
// cout<<cd<<endl;
htcode['A'+i]=cd; //以结点字符索引哈夫曼编码
// cout<<htcode['A'+i];
}
}
哈夫曼树的创建
最新推荐文章于 2023-02-13 23:28:42 发布