国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

Huffman coding

2019-11-08 01:43:34
字體:
供稿:網(wǎng)友

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.

 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 Copy sample input to clipboard
50 51 42 63 24 3Sample Output
45Hint0: 011: 002: 113: 1004: 101這道題是哈夫曼編碼,主要是優(yōu)先隊列沒用好,數(shù)據(jù)類型的指針變量應(yīng)該這么傳參才能小根堆,如果是普通變量可以直接在結(jié)構(gòu)體里重載 < 即可,其余沒什么
#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);    }//將字符存進優(yōu)先隊列     /*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;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 和静县| 保康县| 溆浦县| 揭西县| 西乡县| 阜康市| 利津县| 富源县| 东至县| 高雄县| 衡水市| 宜丰县| 仁寿县| 邳州市| 正安县| 双流县| 化州市| 花垣县| 利津县| 青田县| 彰化市| 盐边县| 宁蒗| 钦州市| 广东省| 玛纳斯县| 东乡县| 儋州市| 桂平市| 英山县| 富顺县| 团风县| 丰顺县| 象山县| 镇平县| 团风县| 八宿县| 东乌珠穆沁旗| 翁源县| 五家渠市| 凤山县|