Pagini recente » Cod sursa (job #3214495) | Cod sursa (job #321409) | Cod sursa (job #2467153) | Cod sursa (job #3148506) | Cod sursa (job #1997638)
#include <iostream>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
bool stiva[123];
int istiva;
class huffman{
public:
huffman *lf, *rg;
bool is_leaf;
unsigned long long times;
huffman() : lf(NULL), rg(NULL), is_leaf(true), times(NULL) {}
huffman(unsigned long long _times) : lf(NULL), rg(NULL), is_leaf(true), times(_times) {}
huffman(unsigned long long _times, huffman *_lf, huffman *_rg) : lf(_lf), rg(_rg), is_leaf(false), times(_times) {}
};
unsigned long long rez(huffman *root){
if(root -> is_leaf){
return 0;
}
return rez(root -> lf) + rez(root -> rg) + root -> times;
}
int b2_to_b10(bool *begin, bool *end){
int rez = 0;
for(int i = istiva - 1; begin != end; i--){
rez += (1 << i) * (*begin++);
}
return rez;
}
void go_lf_rg(huffman *root){
if(root -> is_leaf){
fout<<istiva<<" " <<b2_to_b10(stiva, stiva + istiva)<<"\n";
return;
}
stiva[istiva++] = 0;
go_lf_rg(root -> lf);
istiva--;
stiva[istiva++] = 1;
go_lf_rg(root -> rg);
istiva--;
return;
}
int main(){
huffman *root, *lf, *rg;
queue < int > qf;
queue < huffman* > qn;
int n, x;
fin>>n;
while(n--){
fin>>x;
qf.push(x);
}
while(true){
if(qf.empty()){
lf = qn.front();
qn.pop();
}
else if(qn.empty()){
lf = new huffman(qf.front());
qf.pop();
}
else if(qf.front() <= qn.front() -> times){
lf = new huffman(qf.front());
qf.pop();
}
else{
lf = qn.front();
qn.pop();
}
if(qf.empty() && qn.empty()){
root = lf;
break;
}
if(qf.empty()){
rg = qn.front();
qn.pop();
}
else if(qn.empty()){
rg = new huffman(qf.front());
qf.pop();
}
else if(qf.front() <= qn.front() -> times){
rg = new huffman(qf.front());
qf.pop();
}
else{
rg = qn.front();
qn.pop();
}
root = new huffman(lf -> times + rg -> times, lf, rg);
qn.push(root);
}
istiva = 0;
fout<<rez(root)<<"\n";
go_lf_rg(root);
return 0;
}