Pagini recente » Cod sursa (job #1423537) | Cod sursa (job #2819235) | Cod sursa (job #117290) | Cod sursa (job #1061026) | Cod sursa (job #2246760)
#include <fstream>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
ifstream f("huffman.in");
ofstream g("huffman.out");
struct Nod { int pos, val; Nod *next, *left, *right; };
bool cmp(Nod* x, Nod* y)
{
return x->val > y->val;
}
int n, i;
long long unsigned a[1000001];
long long unsigned len[1000001];
long long unsigned code[1000001];
Nod* Huffman(std::vector<Nod*>& heap)
{
while (heap.size()>1)
{
Nod *c1 = heap.front();
std::pop_heap (heap.begin(), heap.end(), cmp); heap.pop_back();
Nod *c2 = heap.front();
std::pop_heap (heap.begin(), heap.end(), cmp); heap.pop_back();
Nod* p = new Nod;
p->val = c1->val + c2->val;
p->left = c1;
p->right = c2;
heap.push_back(p); std::push_heap (heap.begin(), heap.end(), cmp);
}
return heap.front();
}
void DepthFirst(Nod* nod, long long int val = 0, int length = 0)
{
if (nod->left != NULL)
{
DepthFirst(nod->left, val * 2, length + 1);
}
if (nod->right != NULL)
{
DepthFirst(nod->right, val * 2 + 1, length + 1);
}
if (nod->right == NULL && nod->left == NULL)
{
len[nod->pos] = length;
code[nod->pos] = val;
}
}
std::vector<Nod*> heap;
int main()
{
f >> n;
for (i = 0; i<n; i++)
{
f >> a[i];
Nod *nod = new Nod;
nod->pos = i;
nod->val = a[i];
nod->left = NULL;
nod->right = NULL;
heap.push_back(nod); std::push_heap (heap.begin(), heap.end());
}
std::make_heap (heap.begin(), heap.end(), cmp);
Nod* root;
root = Huffman(heap);
DepthFirst(root);
long long unsigned lg = 0;
for (i = 0; i < n; i++)
{
lg += len[i] * a[i];
}
g << lg << '\n';
for (i = 0; i < n; i++)
{
g << len[i] << ' ' << code[i] << '\n';
}
f.close();
g.close();
return 0;
}