贪心1003 POJ 1521-Entropy

来源:互联网 发布:英伦风男装品牌知乎 编辑:程序博客网 时间:2024/05/21 09:09
典型HUFFMAN树的问题,用了STL的priority_queue
#include <iostream>  #include <string>  #include <queue>    using namespace std;    class node{  public:      int key; //a,b,c...      int count;//频率      int p;//父亲结点      friend bool operator < (const node &a, const node &b)      {          if(b.count < a.count)              return true;          else              return false;      }  };    int value(char c)  {      if(c=='_')          return 26;      else          return(c-'A');  }    int main()  {      string str;      cin >> str;      while(str!="END")      {          node c[60];          for(int i=0;i<60;i++)          {              c[i].key=i;              c[i].count=0;          }          int length=str.length();          priority_queue<node> q;          for(int i=0;i<length;i++)          {              (c[value(str.at(i))]).count++;          }          for(int i=0;i<=26;i++)          {              if(c[i].count!=0)                  q.push(c[i]);          }          if(q.size()==1)          {              printf("%d %d 8.0/n",8*length,length);          }          else          {              int n=27;              while(q.size()>1)              {                  node s1=q.top();                  q.pop();                  node s2=q.top();                  q.pop();                  c[n].count=s1.count+s2.count;                  c[s1.key].p=n;                  c[s2.key].p=n;                  q.push(c[n]);                  n++;              }              int cnt=0;              for(int i=0;i<=26;i++)              {                  if(c[i].count!=0)                  {                      int height=1;                      int parent=c[i].p;                      while(parent!=n-1)                      {                          height++;                          parent=c[parent].p;                      }                      cnt+=height*c[i].count;                  }              }              printf("%d %d %.1lf/n",8*length,cnt,(((double)(8*length))/((double)cnt)));          }          cin >> str;      }  }  

0 0