#include<bits/stdc++.h>
using namespace std;
struct node{//树结构体
int w;//权重(即该字符在文本中出现的次数)
node *l; node *r;//左右子树
bool is;//是否是叶子节点
char c;//字符
};
struct cmp{
bool operator ()(node *a,node *b){
return a->w > b->w;
}
};
void setValue(node* &tmp, int _w, node* a, node *b, bool _is, char _c) {//赋值函数
tmp->w = _w; tmp->l = a; tmp->r = b; tmp->is = _is; tmp->c = _c;
}
void fu(node *n,string ss){//dfs输出哈夫曼编码
if(n->is) {cout<<n->c<<"的出现次数为"<<n->w<<","<<" 哈夫曼编码为"<<ss<<""<<endl;return;}//如果是叶子节点就输出字符以及编码
if(n->l) fu(n->l,ss+"0");//如果有左子树,继续递归搜索左子树,同时要传入更新过的哈夫曼编码
if(n->r) fu(n->r,ss+"1");//如果有右子树,继续递归搜索右子树,同时要传入更新过的哈夫曼编码
return;
}
int main(){
string s; printf("请输入你的文本\n"); cin>>s;
string ss="";
map<char, int> ma;//每个字符和他的权重(即该字符在文本中出现的次数)
priority_queue<node *,vector<node*>,cmp >qu;//优先队列便于给各个节点按照权重大小排序
map<char,int>::iterator it;//迭代器
int num = 0;//最小带权路径长度初始化为0
for(int i = 0; i < s.length(); i++){
if(ma.count(s[i])) ma[s[i]]++;//如果出现过,则对应的次数加一
else ma[s[i] ] = 1;//如果没有出现过,次数为1
}
for(it = ma.begin(); it != ma.end(); it++){
node *h = (node*)malloc(sizeof(node));
setValue(h, it->second,NULL,NULL,true,it->first);
qu.push(h);//加入优先队列
}
while(qu.size()>1){//当优先队列中的元素多于一个的时候
int n1 = (qu.top())->w;//n1赋值为最小的权重
node *h1 = qu.top();//h1指向权重最小的节点
qu.pop();//将该节点弹出
int n2 = (qu.top())->w;//n2赋值为第二小的权重(第一小的在上一行被弹出了)
node *h2 = qu.top();//h2指向权重第二小的节点
qu.pop();//将该节点弹出
int tmp = n1+n2;//目前带权路径长度为n1+n2
node *n3 = (node*)malloc(sizeof(node*));
setValue(n3,tmp,h1,h2,false,0);//新建根节点
qu.push(n3);//加入优先队列
num+=tmp;
}
node*n3 = qu.top();
printf("最小带权路径长度为%d\n",num);
fu(n3,ss);
}