Pagini recente » Cod sursa (job #484851) | Cod sursa (job #279733) | Cod sursa (job #2002504) | Cod sursa (job #2367059) | Cod sursa (job #2791008)
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
ifstream in("huffman.in");
ofstream out("huffman.out");
struct Nod
{
Nod* st;
Nod* dr;
int val, frq;
Nod(int val, int frq)
{
st = dr = NULL;
this->val = val;
this->frq = frq;
}
};
struct compare
{
bool operator()(Nod* st, Nod* dr)
{
return st->frq > dr->frq;
}
};
int n,a;
priority_queue<Nod*, vector<Nod*>, compare> pq;
vector<pair<int, pair<int,int>>> dap;
int rasp;
void Parcurgere(struct Nod* Radacina, string s)
{
if (!Radacina)
{
return ;
}
if (Radacina->val != -1)
{
int acm = 0;
int j = 0;
rasp += Radacina->frq * s.length();
for (int i=s.length()-1; i>=0; i--)
{
acm = acm + (s[i] - '0') * (1<<j);
j++;
}
///cout << Radacina->val << " " << acm << "\n";
dap.push_back({Radacina->val, {acm, s.length()}});
}
Parcurgere(Radacina->st, s + "0");
Parcurgere(Radacina->dr, s + "1");
}
int main()
{
in >> n;
for (int i=1; i<=n; i++)
{
in >> a;
pq.push(new Nod(i, a));
}
struct Nod *left, *right, *top;
while(pq.size() != 1)
{
left = pq.top();
pq.pop();
right = pq.top();
pq.pop();
top = new Nod(-1, left->frq + right->frq);
top->st = left;
top->dr = right;
pq.push(top);
}
Parcurgere(pq.top(), "");
out << rasp << "\n";
sort(dap.begin(), dap.end());
for (auto y:dap)
{
out << y.second.second << " " << y.second.first << "\n";
}
return 0;
}