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 characterc, and dT(c) is be the depth of characterc's leaf in the treeT.
InputThe first line is the number of characters n.
The following n lines, each line gives the character c and its frequencyf(c).
OutputOutput a single number B(T).
Sample Input50 51 42 63 24 3Sample Output45Hint0: 011: 002: 113: 1004: 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;}
新闻热点
疑难解答