Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <functional>
- #include <vector>
- using namespace std;
- struct node
- {
- int prior;
- int w;
- bool occupied;
- node * left;
- node * right;
- node (int val,int priority): prior(priority), w(val), occupied(true), left(NULL), right(NULL) {};
- node (node *l, node *r): prior(l->prior + r->prior), occupied(false), left(l), right(r) {};
- };
- node * build_tree(string s)
- {
- node * l, *r;
- int tab[26]={};
- for (int i=0;i<s.length();i++)
- tab[ s[i] - 'a']++;
- auto f=[](node * a, node *b) {return a->prior >= b->prior;};
- priority_queue <node *, vector<node*>, decltype(f)> Q (f);
- for (int i=0;i<26;i++)
- if (tab[i]!=0)
- Q.push(new node (i,tab[i]));
- while (Q.size()>1)
- {
- l=Q.top();
- Q.pop();
- r=Q.top();
- Q.pop();
- Q.push(new node(l,r));
- }
- return Q.top();
- }
- //UTILITY:
- void save (node * p, string * tab, string ind)
- {
- if (p==NULL) return;
- if (p->occupied)
- tab[p->w]=ind;
- save(p->left,tab,ind+'0');
- save(p->right,tab,ind+'1');
- }
- string * kody(string s)
- {
- node * p= build_tree(s);
- string * tab=new string [26];
- for (int i=0;i<26;i++) tab[i]="empty";
- save(p,tab,"");
- return tab;
- }
- int main ()
- {
- string input;
- string * tab;
- cin >> input;
- tab=kody(input);
- for (int i=0;i<26;i++)
- if (tab[i]!="empty")
- cout << "litera: " <<(char) (i+'a') << " kod: " << tab[i] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement