Advertisement
warrior98

Untitled

Jun 3rd, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int fr[128];
  6.  
  7. struct node {
  8.     node *st, *dr;
  9.     char ch;
  10.     int freq;
  11.  
  12.     node(char CH, int FREQ) {
  13.         st=dr=NULL;
  14.         ch = CH;
  15.         freq = FREQ;
  16.     }
  17. };
  18.  
  19. struct Compare {
  20.     bool operator()(const node* lhs, const node* rhs) const {
  21.         return lhs->freq > rhs->freq;
  22.     }
  23. };
  24.  
  25. string codes[128];
  26.  
  27. void find_codes(node *root, string code) {
  28.     if(root->ch != 0)
  29.         codes[root->ch] = code;
  30.  
  31.     if(root->st != NULL)
  32.         find_codes(root->st, code+"0");
  33.    
  34.     if(root->dr != NULL)
  35.         find_codes(root->dr, code+"1");
  36. }
  37.  
  38. void encode(string text) {
  39.     memset(fr, 0, sizeof(fr));
  40.  
  41.     for(auto it:text) ++fr[it];
  42.  
  43.     priority_queue<node*, vector<node*>, Compare > pq;
  44.     for(int i=1;i<128;++i)
  45.         if(fr[i])
  46.             pq.push(new node((char)i, fr[i]));
  47.  
  48.     while(pq.size() > 1) {
  49.         node* x = pq.top();
  50.         pq.pop();
  51.         node* y = pq.top();
  52.         pq.pop();
  53.  
  54.         int freq = x->freq + y->freq;
  55.         node *newNode = new node(0, freq);
  56.  
  57.         newNode->st = x;
  58.         newNode->dr = y;
  59.  
  60.         pq.push(newNode);
  61.     }
  62.  
  63.     find_codes(pq.top(), "");
  64. }
  65.  
  66. int main()
  67. {
  68.     string text = "text de text";
  69.     encode(text);
  70.  
  71.     for(auto it:text) cout << it << ' ' << codes[it] << '\n';
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement