zoukankan      html  css  js  c++  java
  • hdoj 1053 Entropy(用哈夫曼编码)优先队列

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1053

    讲解:

      题意:给定一个字符串,根据哈夫曼编码求出最短长度,并求出比值。

         思路:就是哈夫曼编码。把单个字符出现次数作为权值。

    AC代码:

     1 #include <iostream>
     2 #include <string>
     3 #include <queue>
     4 #include <cstdio>
     5 using namespace std;
     6 
     7 class node{
     8 public:
     9     int key; //a,b,c...
    10     int count;//频率
    11     int p;//父亲结点
    12     friend bool operator < (const node &a, const node &b)
    13     {
    14         if(b.count < a.count)
    15             return true;
    16         else
    17             return false;
    18     }
    19 };
    20 
    21 int value(char c)
    22 {
    23     if(c=='_')
    24         return 26;
    25     else
    26         return(c-'A');
    27 }
    28 int main()
    29 {
    30     string str;
    31     cin >> str;
    32     while(str!="END")
    33     {
    34         node c[60];
    35         for(int i=0;i<60;i++)
    36         {
    37             c[i].key=i;
    38             c[i].count=0;
    39         }
    40         int length=str.length();
    41         priority_queue<node> q;
    42         for(int i=0;i<length;i++)
    43         {
    44             (c[value(str.at(i))]).count++;
    45         }
    46         for(int i=0;i<=26;i++)
    47         {
    48             if(c[i].count!=0)
    49                 q.push(c[i]);
    50         }
    51         if(q.size()==1)
    52         {
    53             printf("%d %d 8.0
    ",8*length,length);
    54         }
    55         else
    56         {
    57             int high=0;
    58             int n=27;
    59             while(q.size()>1)
    60             {
    61                 node s1=q.top();
    62                 q.pop();
    63                 node s2=q.top();
    64                 q.pop();
    65                 c[n].count=s1.count+s2.count;
    66                 c[s1.key].p=n;
    67                 c[s2.key].p=n;
    68                 high=high+c[n].count;
    69                 q.push(c[n]);
    70                 n++;
    71             }
    72             printf("%d %d %.1lf
    ",8*length,high,(((double)(8*length))/((double)high)));
    73         }
    74         cin >> str;
    75     }
    76 }
  • 相关阅读:
    cocos2d-x之物理引擎初试
    cocos2d-x之猜数字游戏
    cocos2d-x之加法计算器
    cocos2d-x之悦动的小球
    cocos2d-x之多个移动的小球
    cocos2d-x之json文件读取初试
    cocos2d-x之xml文件读取初试
    cocos2d-x之使用plist文件初试
    cocos2d-x之文件读写
    cocos2d-x之首选项数据初试
  • 原文地址:https://www.cnblogs.com/lovychen/p/3833221.html
Copyright © 2011-2022 走看看