Pagini recente » Cod sursa (job #1796809) | Cod sursa (job #1504270) | Cod sursa (job #1907898) | Cod sursa (job #549331) | Cod sursa (job #1307860)
#include <algorithm>
#include <fstream>
#include <queue>
#include <vector>
#include <memory>
#include <map>
using namespace std;
struct Node;
typedef shared_ptr<Node> node_t;
struct Node {
int w;
node_t left;
node_t right;
Node(int w, node_t left = nullptr, node_t right = nullptr)
: w {w}, left {left}, right {right}
{}
};
struct cmp_greater {
bool operator()(const node_t& a, const node_t& b) {
return a->w > b->w;
}
};
int df(node_t node, map<int, vector<int>>& alph, int rep = 0, int h = 0) {
while (node->left && node->right)
return node->w +
df(node->left, alph, rep << 1, h + 1) +
df(node->right, alph, (rep << 1) + 1, h + 1);
alph[h].push_back(rep);
return 0;
}
int main() {
ifstream fin("huffman.in");
ofstream fout("huffman.out");
int n; fin >> n;
// min priority queue
priority_queue<node_t, vector<node_t>, cmp_greater> Q;
for (int x; n--;) {
fin >> x;
Q.push(make_shared<Node>(x));
}
// build Huffman tree
while (Q.size() > 1) {
node_t l = Q.top(); Q.pop();
node_t r = Q.top(); Q.pop();
Q.push(make_shared<Node>(l->w + r->w, l, r));
}
map<int, vector<int>> alph;
fout << df(Q.top(), alph) << '\n';
for (auto it = alph.rbegin(); it != alph.rend(); ++it)
for (auto rep : it->second)
fout << (it->first) << ' ' << rep << '\n';
return 0;
}