国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 怀宁县| 定襄县| 云林县| 玉环县| 东台市| 石泉县| 冕宁县| 横峰县| 台安县| 平遥县| 湘潭市| 涡阳县| 彰化市| 霞浦县| 马尔康县| 内丘县| 平原县| 富源县| 若羌县| 卫辉市| 阳朔县| 石门县| 林周县| 泸定县| 新泰市| 金寨县| 文化| 福泉市| 杭州市| 华亭县| 桐柏县| 五台县| 田东县| 从江县| 丹阳市| 汪清县| 清水河县| 鄂托克前旗| 徐汇区| 阜南县| 行唐县|