Pagini recente » Cod sursa (job #2200606) | Cod sursa (job #2181494) | Cod sursa (job #1450274) | Cod sursa (job #3235282) | Cod sursa (job #2908556)
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <queue>
#include <algorithm>
using namespace std;
struct nod {
int weight;
int left;
int right;
};
long long dfs(
int in, int depth, long long cod,
const vector<nod> &noduri,
vector<int> &code_lengths,
vector<long long> &code_values)
{
const nod &curr = noduri[in];
if (curr.left == -1) {
code_lengths[in] = depth;
code_values[in] = cod;
return (long long) depth * curr.weight;
}
else {
return dfs(curr.left, depth+1, cod << 1, noduri, code_lengths, code_values)
+ dfs(curr.right, depth+1, (cod << 1) + 1, noduri, code_lengths, code_values);
}
}
int select(queue<int> &q1, queue<int> &q2, const vector<nod> &noduri)
{
int rez;
if (q1.size() == 0) {
rez = q2.front();
q2.pop();
}
else if (q2.size() == 0) {
rez = q1.front();
q1.pop();
}
else if (noduri[q1.front()].weight < noduri[q2.front()].weight) {
rez = q1.front();
q1.pop();
}
else {
rez = q2.front();
q2.pop();
}
return rez;
}
int main()
{
ifstream fin("huffman.in");
ofstream fout("huffman.out");
int n;
fin >> n;
vector<nod> noduri(n);
vector<int> code_length(n);
vector<long long> code_values(n);
//priority_queue<nod*, deque<nod*>, MyComparison> pq;
queue<int> before, after;
for (int i = 0; i < n; ++i) {
nod a;
a.left = a.right = -1;
fin >> a.weight;
noduri[i] = a;
before.push(i);
}
while (before.size() > 0 || after.size() > 1) {
int in1 = select(before, after, noduri);
int in2 = select(before, after, noduri);
nod nou;
nou.weight = noduri[in1].weight + noduri[in2].weight;
nou.left = in1;
nou.right = in2;
noduri.push_back(nou);
after.push(noduri.size() - 1);
}
int iroot = after.front();
long long total = dfs(iroot, 0, 0, noduri, code_length, code_values);
fout << total << "\n";
for (int i = 0; i < n; ++i) {
fout << code_length[i] << " " << code_values[i] << "\n";
}
return 0;
}