Guest User

Untitled

a guest
May 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <memory>
  6.  
  7. struct Node {
  8. Node(const std::string& name, int prob) : name(name), prob(prob) { }
  9. Node(std::unique_ptr<Node>&& left, std::unique_ptr<Node>&& right) {
  10. prob = left->prob + right->prob;
  11. this->left = std::move(left);
  12. this->right = std::move(right);
  13. }
  14. std::string name;
  15. std::unique_ptr<Node> left;
  16. std::unique_ptr<Node> right;
  17. int prob;
  18. };
  19.  
  20. void view_tree(const Node* node, int indent) {
  21. if (!node) return;
  22. for (int i = 0; i < indent; i++)
  23. std::cout << " ";
  24. if (!node->name.empty())
  25. std::cout << node->name << " ";
  26. std::cout << "(" << node->prob << ")" << std::endl;
  27. view_tree(node->left.get(), indent + 1);
  28. view_tree(node->right.get(), indent + 1);
  29. }
  30.  
  31. void view_code(const Node* node, std::string code) {
  32. if (!node) return;
  33. if (!node->name.empty())
  34. std::cout << node->name << "\t" << code << std::endl;
  35. view_code(node->left.get(), code + "0");
  36. view_code(node->right.get(), code + "1");
  37. }
  38.  
  39. void encode(std::vector<std::unique_ptr<Node>>& nodes) {
  40. auto priority = [](const std::unique_ptr<Node>& x, const std::unique_ptr<Node>& y) { return x->prob < y->prob; };
  41. while (nodes.size() > 1) {
  42. auto most_min_it = std::min_element(nodes.begin(), nodes.end(), priority);
  43. auto most_min = std::move(*most_min_it);
  44. nodes.erase(most_min_it);
  45. auto most_min2_it = std::min_element(nodes.begin(), nodes.end(), priority);
  46. auto most_min2 = std::move(*most_min2_it);
  47. nodes.erase(most_min2_it);
  48. nodes.emplace_back(std::make_unique<Node>(std::move(most_min), std::move(most_min2)));
  49. }
  50. }
  51.  
  52. int main(void) {
  53. std::vector<std::unique_ptr<Node>> nodes;
  54. do {
  55. std::string name;
  56. std::cout << "name: ";
  57. std::cin >> name;
  58. if (name.empty()) {
  59. std::cout << std::endl;
  60. break;
  61. }
  62. int prob;
  63. std::cout << "prob: ";
  64. std::cin >> prob;
  65. nodes.emplace_back(std::make_unique<Node>(name, prob));
  66. } while (1);
  67. if (nodes.empty()) {
  68. std::cerr << "Number of nodes must be greater than 0." << std::endl;
  69. return EXIT_FAILURE;
  70. }
  71.  
  72. encode(nodes);
  73.  
  74. std::cout << std::endl;
  75. std::cout << "tree" << std::endl;
  76. view_tree(nodes.front().get(), 0);
  77.  
  78. std::cout << std::endl;
  79. std::cout << "code" << std::endl;
  80. view_code(nodes.front().get(), std::string());
  81. return EXIT_SUCCESS;
  82. }
Add Comment
Please, Sign In to add comment