Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- ifstream in("t.in");
- ofstream out("t.out");
- unordered_map<char, int> M;
- struct Node
- {
- string simbol;
- int freq;
- Node* left_child;
- Node* right_child;
- Node(string c, int x)
- {
- simbol = c;
- freq = x;
- left_child = right_child = NULL;
- }
- ~Node()
- {
- cout <<"destructor apelat!\n";
- }
- };
- class greaterr
- {
- public:
- bool operator()(Node* first, Node* second) const
- {
- return first -> freq > second -> freq;
- }
- };
- vector<pair<string, string>> A;
- void Traversal(Node* nod, string bins)
- {
- // cout << depth << '\n';
- if(nod -> left_child)
- {
- Traversal(nod -> left_child, bins + "0");
- }
- if(nod -> right_child)
- {
- Traversal(nod -> right_child, bins + "1");
- }
- if(!nod -> left_child && !nod -> right_child)
- {
- A.push_back({nod -> simbol, bins});
- delete nod;
- }
- }
- int main()
- {
- string S;
- getline(in, S);
- for(int i = 0; i < (int)S.size(); ++i)
- M[S[i]]++;
- priority_queue<Node*, vector<Node*>, greaterr> Q;
- Node* nod;
- for(auto i : M)
- {
- string c;
- c += i.first;
- nod = new Node(c, i.second);
- Q.push(nod);
- }
- Node *left, *right, *father;
- while(Q.size() > 1)
- {
- left = Q.top();
- Q.pop();
- right = Q.top();
- Q.pop();
- father = new Node("", left -> freq + right -> freq);
- father -> left_child = left;
- father -> right_child = right;
- Q.push(father);
- }
- Node* Tata = Q.top();
- string bins = "";
- Traversal(Tata, bins);
- for(auto i : A)
- {
- out << i.first << " " << i.second << '\n';
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement