Pagini recente » Cod sursa (job #1673040) | Cod sursa (job #1281275) | Cod sursa (job #583906) | Cod sursa (job #681668) | Cod sursa (job #885484)
Cod sursa(job #885484)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <deque>
using namespace std;
typedef unsigned long long ull;
struct node {
node() { data=-1; freq=1<<30; }
int child[2];
ull freq;
int data;
};
vector<node> a;
node hufftree() {
int n=a.size();
int fr1=0, fr2=n;
for (int j=1; j<n; ++j) {
a.push_back(node());
for (int i=0; i<2; ++i) {
if (fr1==n || a[fr2].freq < a[fr1].freq) {
a.back().child[i]=fr2++;
}
else {
a.back().child[i]=fr1++;
}
}
a.back().freq = a[a.back().child[0]].freq + a[a.back().child[1]].freq;
}
return a.back();
}
void store(vector<ull> & code, node tmp, ull num, ull & len) {
len+=tmp.freq;
if (tmp.data!=-1) {
code[tmp.data]=num;
return;
}
store(code, a[tmp.child[0]], num<<1, len);
store(code, a[tmp.child[1]], (num<<1)+1, len);
}
int main() {
ifstream fin("huffman.in");
ofstream fout("huffman.out");
int n; fin >> n;
a.reserve(2*n);
a.resize(n);
for (int i=0; i<n; ++i) {
a[i].data=i;
fin >> a[i].freq;
}
node root=hufftree();
vector<ull> code(n);
ull len=0;
store(code, root, 1ull, len);
fout << len-root.freq << '\n';
for (int i=0; i<n; ++i) {
unsigned int tmp=63-__builtin_clzll(code[i]);
fout << tmp << ' ' << (code[i]^(1ull<<tmp)) << '\n';
}
return 0;
}