Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #define FAST_ALLOCATOR_MEMORY 1e8
  2. #include <iostream>
  3. #include <fstream>
  4. #include <unordered_map>
  5. #include <vector>
  6. #include <queue>
  7. #include "optimization.h"
  8.  
  9. using namespace std;
  10.  
  11. struct Node {
  12.     char data;
  13.     int freq;
  14.     Node *left, *right;
  15. };
  16.  
  17. Node* add_node(char data, int freq, Node* left, Node* right) {
  18.     Node* node = new Node;
  19.     node->data = data;
  20.     node->freq = freq;
  21.     node->left = left;
  22.     node->right = right;
  23.     return node;
  24. }
  25.  
  26. auto cmp = [](Node* a, Node* b) {
  27.     return a->freq > b->freq;
  28. };
  29.  
  30. void encode(Node* root, const string& str, unordered_map<char, string>& codes_map) {
  31.     if (root == nullptr) return;
  32.     if (!root->left && !root->right)
  33.         codes_map[root->data] = str;
  34.     encode(root->left, str + "0", codes_map);
  35.     encode(root->right, str + "1", codes_map);
  36. }
  37.  
  38. void build(const string& text) {
  39.     unordered_map<char, int> freq;
  40.     for (char data: text)
  41.         freq[data]++;
  42.     priority_queue<Node*, vector<Node*>, decltype(cmp)> q(cmp);
  43.     for (auto pair: freq)
  44.         q.push(add_node(pair.first, pair.second, nullptr, nullptr));
  45.     while (q.size() != 1) {
  46.         Node *left = q.top();
  47.         q.pop();
  48.         Node *right = q.top();
  49.         q.pop();
  50.         int sum = left->freq + right->freq;
  51.         q.push(add_node('\0', sum, left, right));
  52.     }
  53.     Node* root = q.top();
  54.     unordered_map<char, string> codes_map;
  55.     encode(root, "", codes_map);
  56.     string str;
  57.     for (auto data: text) {
  58.         str += codes_map[data];
  59.     }
  60.     cout << codes_map.size() << " " << str.size() << "\n";
  61.     for (const auto& pair: codes_map) {
  62.         cout << pair.first << ": " << pair.second << '\n';
  63.     }
  64.     cout << str << '\n';
  65. }
  66.  
  67.  
  68. int main() {
  69. #ifdef LOCAL_DEFINE
  70.     ifstream in("input.txt");
  71. #endif
  72.     ios_base::sync_with_stdio(0);
  73.     cin.tie(0);
  74.     cout.tie(0);
  75.     string text;
  76.     in >> text;
  77.     if (text.size() == 1) {
  78.         cout << 1 << " " << 1 << "\n";
  79.         cout << text << ": 0\n0";
  80.     } else build(text);
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement