Advertisement
Guest User

Untitled

a guest
Apr 25th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <functional>
  4. #include <vector>
  5. using namespace std;
  6. struct node
  7. {
  8.     int prior;
  9.     int w;
  10.     bool occupied;
  11.     node * left;
  12.     node * right;
  13.     node (int val,int priority): prior(priority), w(val), occupied(true), left(NULL), right(NULL) {};
  14.     node (node *l, node *r): prior(l->prior + r->prior), occupied(false), left(l), right(r) {};
  15. };
  16.  
  17. node * build_tree(string s)
  18. {
  19.     node * l, *r;
  20.     int tab[26]={};
  21.     for (int i=0;i<s.length();i++)
  22.         tab[ s[i] - 'a']++;
  23.     auto f=[](node * a, node *b) {return a->prior >= b->prior;};
  24.     priority_queue <node *, vector<node*>, decltype(f)> Q (f);
  25.     for (int i=0;i<26;i++)
  26.         if (tab[i]!=0)
  27.             Q.push(new node (i,tab[i]));
  28.     while (Q.size()>1)
  29.     {
  30.         l=Q.top();
  31.         Q.pop();
  32.         r=Q.top();
  33.         Q.pop();
  34.         Q.push(new node(l,r));
  35.     }
  36.     return Q.top();
  37. }
  38.  
  39. //UTILITY:
  40.  
  41. void save (node * p, string * tab, string ind)
  42. {
  43.     if (p==NULL) return;
  44.     if (p->occupied)
  45.         tab[p->w]=ind;
  46.     save(p->left,tab,ind+'0');
  47.     save(p->right,tab,ind+'1');
  48. }
  49. string * kody(string s)
  50. {
  51.     node * p= build_tree(s);
  52.  
  53.     string * tab=new string [26];
  54.     for (int i=0;i<26;i++) tab[i]="empty";
  55.     save(p,tab,"");
  56.     return tab;
  57. }
  58. int main ()
  59. {
  60.     string input;
  61.     string * tab;
  62.     cin >> input;
  63.     tab=kody(input);
  64.     for (int i=0;i<26;i++)
  65.         if (tab[i]!="empty")
  66.             cout << "litera: " <<(char) (i+'a') << " kod: " << tab[i] << endl;
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement