In computer science and information theory, a Huffman code is an optimal prefix code algorithm.
In this exercise, please use Huffman coding to encode a given data.
You should output the number of bits, denoted asB(T), to encode the data:
B(T)=∑f(c)dT(c),
wheref(c) is the frequency of character c, and dT(c) is be the depth of characterc's leaf in the tree T.
Input
The first line is the number of characters n.
The following n lines, each line gives the character c and its frequencyf(c).
Output
Output a single number B(T).
Sample Input
5 0 5 1 4 2 6 3 2 4 3
Sample Output
45
Hint
0: 01
1: 00
2: 11
3: 100
4: 101
这道题是哈夫曼编码,主要是优先队列没用好,数据类型的指针变量应该这么传参才能小根堆,如果是普通变量可以直接在结构体里重载 < 即可,其余没什么
#include <iostream>
#include <queue>
#include <map>
using namespace std;
struct huffman{
char c;
int num;
};
struct tree{
huffman h;
tree* left;
tree* right;
};
struct cmp{
bool operator() (tree const*a, tree const*b){
return a->h.num > b->h.num;
}
};//小根堆比较
map <char,int> mm;
void deal(tree* t,int n){
if(t->left==NULL&&t->right==NULL){
mm[t->h.c]=n;
}
else {
deal(t->left,n+1);
deal(t->right,n+1);
}
}//计算树的深度,用于计算字符长度
int main()
{
int n;
cin >> n;
priority_queue <tree*, vector<tree*>, cmp> pq;
huffman hu[1001];
for(int i=0; i < n; ++i){
cin >> hu[i].c >> hu[i].num;
tree *tmp=new tree;
tmp->h=hu[i];
tmp->left=NULL;
tmp->right=NULL;
pq.push(tmp);
}//将字符存进优先队列
/*tree* t=pq.top();
cout << t->h.c << endl; */
while(pq.size() > 1){
tree* t1=pq.top();
//cout << t1->h.c << " "<<t1->h.num << endl;
pq.pop();
tree* t2=pq.top();
//cout << t2->h.c << " "<< t2->h.num << endl;
pq.pop();
tree *tmp=new tree;
tmp->h.c='.';
tmp->h.num=t1->h.num+t2->h.num;
tmp->left=t1;
tmp->right=t2;
pq.push(tmp);
//cout << endl;
}//建立哈夫曼编码树
tree* res=pq.top();
//cout << res->h.num << endl;
deal(res,0);
int resu=0;
for(int i=0; i < n; ++i){
//cout << hu[i].num << " " << mm[hu[i].c] << endl;
resu+=(hu[i].num*(mm[hu[i].c]));
}
cout << resu << endl;
}