歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++使用優先隊列來構建huffman樹[哈夫曼樹]

C++使用優先隊列來構建huffman樹[哈夫曼樹]

日期:2017/3/1 10:35:59   编辑:Linux編程
  1. #include <iostream>
  2. #include <queue>
  3. #include <string.h>
  4. #include <vector>
  5. #include <algorithm>
  6. using namespace std;
  7. char Table[26];
  8. struct Node
  9. {
  10. int freq;
  11. char val;
  12. Node * left;
  13. Node * right;
  14. Node():left(NULL), right(NULL) , freq(0) , val('0'){}
  15. };
  16. class Cmp
  17. {
  18. public:
  19. bool operator() (const Node * a, const Node * b) const
  20. {
  21. return a->freq > b->freq; // 從小到大 ,freq 小的 優先級別高
  22. }
  23. };
  24. priority_queue<Node* , vector<Node*> , Cmp> myQueue;
  25. void BuildTree()
  26. {
  27. for (int i = 0; i < 26; ++ i)
  28. {
  29. if (Table[i] > 0)
  30. {
  31. Node * node = new Node();
  32. node->freq = Table[i];
  33. node->val =(char) (i + 'A');
  34. myQueue.push(node);
  35. }
  36. }
  37. while (myQueue.size() > 1)
  38. {
  39. Node * f = myQueue.top();
  40. myQueue.pop();
  41. Node * s = myQueue.top();
  42. myQueue.pop();
  43. Node * tmp = new Node();
  44. tmp->freq = f->freq + s->freq;
  45. tmp->left = f;
  46. tmp->right = s;
  47. myQueue.push(tmp);
  48. }
  49. //cout << myQueue.top()->freq<<endl;
  50. }
  51. struct PrintNode
  52. {
  53. int freq;
  54. char val;
  55. string code;
  56. };
  57. vector<PrintNode> vpn;
  58. bool cmp(const PrintNode & a , const PrintNode & b)
  59. {
  60. return a.freq > b.freq;
  61. }
  62. void Print( Node * node , string res)
  63. {
  64. if (node == NULL)
  65. {
  66. return;
  67. }
  68. if (node->val != '0')
  69. {
  70. PrintNode pn;
  71. pn.val = node->val;
  72. pn.freq = node->freq;
  73. pn.code = res;
  74. vpn.push_back(pn);
  75. //cout <<node->val <<" | " << node->freq <<" | "<< res <<endl;
  76. return ;
  77. }
  78. Print(node->left , res + "0");
  79. Print(node->right, res + "1");
  80. delete node->left;
  81. delete node->right;
  82. }
  83. int main()
  84. {
  85. int N;
  86. memset(Table , 0 , sizeof(Table));
  87. cin >> N;
  88. for (int i = 0; i < N; ++i)
  89. {
  90. char ch ;
  91. cin >> ch;
  92. if (ch >= 'A' && ch <= 'Z')
  93. {
  94. ++Table[ch - 'A'];
  95. }
  96. }
  97. BuildTree();
  98. Node * root = myQueue.top();
  99. myQueue.pop();
  100. Print(root , "");
  101. sort(vpn.begin() , vpn.end() , cmp);
  102. for (int i = 0; i < vpn.size(); ++i)
  103. {
  104. cout <<vpn[i].val << " "<<vpn[i].freq <<" " << vpn[i].code<<endl;
  105. }
  106. return 0;
  107. }
具體的構成算法不再這裡討論了,
Copyright © Linux教程網 All Rights Reserved