Pagini recente » Cod sursa (job #619009) | Cod sursa (job #3215448) | Cod sursa (job #3223096) | Cod sursa (job #1525534) | Cod sursa (job #885012)
Cod sursa(job #885012)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <deque>
#include <cstring>
#include <cstdlib>
#include <cassert>
using namespace std;
struct node {
node() { data=-1; freq=1<<30; }
node * child[2];
int freq;
int data;
};
node hufftree(deque<node> & a) {
deque<node> b;
while (!a.empty() || b.size()>1) {
b.push_back(node());
for (int i=0; i<2; ++i) {
b.back().child[i]=new node;
if (a.empty() || b.front().freq < a.front().freq) {
*b.back().child[i]=b.front();
b.pop_front();
}
else {
*b.back().child[i]=a.front();
a.pop_front();
}
}
b.back().freq = b.back().child[0]->freq + b.back().child[1]->freq;
}
return b.front();
}
void store(vector<string> & code, node tmp, string s, long long & len) {
len+=tmp.freq;
if (tmp.data!=-1) {
code[tmp.data]=s;
return;
}
store(code,*tmp.child[0],s+'0',len);
store(code,*tmp.child[1],s+'1',len);
}
int main() {
ifstream fin("test7.in");
ofstream fout("huffman.out");
int n; fin >> n;
deque<node> a(n);
for (int i=0; i<n; ++i) {
a[i].data=i;
fin >> a[i].freq;
}
node root=hufftree(a);
vector<string> code(n);
long long len=-root.freq;
store(code, root, "", len);
fout << len << '\n';
for (int i=0; i<n; ++i) {
fout << code[i].length() << ' ' << strtoll(code[i].c_str(),NULL,2) << '\n';
}
return 0;
}