Pagini recente » Cod sursa (job #60910) | Cod sursa (job #2696358) | Cod sursa (job #318011) | Cod sursa (job #1912318) | Cod sursa (job #3234200)
#include <iostream>
#include <fstream>
#include <queue>
std::ifstream fin;
std::ofstream fout;
class Node {
private:
int _symbol;
long _freq;
Node *_left, *_right;
public:
Node(long freq, Node *left = nullptr, Node *right = nullptr) : _symbol(0), _freq(freq), _left(left), _right(right) {}
Node(int symbol, long freq) : _symbol(symbol), _freq(freq), _left(nullptr), _right(nullptr) {}
int symbol()
{
return this->_symbol;
}
long freq()
{
return this->_freq;
}
Node *left()
{
return this->_left;
}
Node *right()
{
return this->_right;
}
bool operator<(Node &other)
{
return this->_freq < other.freq();
}
};
class Node_Comp {
public:
bool operator()(Node *node1, Node *node2)
{
return node1->freq() > node2->freq();
}
};
long long find_encoding(Node *root, int depth, int base10_encoding, std::vector<std::pair<int, int>> &encoding)
{
long long sum = 0;
if (root->symbol()) {
encoding.push_back({depth, base10_encoding});
return sum;
}
sum += find_encoding(root->left(), depth + 1, base10_encoding, encoding);
sum += find_encoding(root->right(), depth + 1, base10_encoding + (1 << depth), encoding);
return sum + root->freq();
}
int main()
{
int n;
std::priority_queue<Node *, std::vector<Node *>, Node_Comp> pq;
Node *root = nullptr;
std::vector<std::pair<int, int>> encoding;
fin.open("huffman.in");
fout.open("huffman.out");
fin >> n;
for (int f, i = 1; i <= n; ++i) {
fin >> f;
pq.push(new Node(i, f));
}
while (pq.size() > 1) {
auto node1 = pq.top();
pq.pop();
auto node2 = pq.top();
pq.pop();
pq.push(new Node(node1->freq() + node2->freq(), node1, node2));
}
root = pq.top();
pq.pop();
fout << find_encoding(root, 0, 0, encoding) << '\n';
for (auto enc : encoding)
fout << enc.first << ' ' << enc.second << '\n';
fin.close();
fout.close();
return 0;
}