Pagini recente » Cod sursa (job #3293843) | Cod sursa (job #3294084) | Cod sursa (job #3274677) | Cod sursa (job #3292860) | Cod sursa (job #3270675)
#include <fstream>
#include <queue>
#include <string>
#include <iostream>
#define inf 1e18 + 1
// stack memory only 8KB or 4KB something like that
std::ifstream in("huffman.in");
std::ofstream out("huffman.out");
std::queue<int> q1, q2;
int n;
const int nmax = 1e6;
long long rez = 0;
long long v[nmax * 2 + 1];
int l[nmax * 2 + 1], r[nmax * 2 + 1];
struct{
long long lungime, cod; // ex cod: 0110, deci lungime = 4, cod(baza10) = 6
}sol[nmax+1]; // nmax+1, since we are interested only in the leaves (distance which is the code 010111.. && the frequency)
void DFS(int nod, int p, long long val){
if(nod <= n){
sol[nod].cod = val;
sol[nod].lungime = p;
rez += v[nod] * p;
return;
}
DFS(l[nod], p + 1, val * 2);
DFS(r[nod], p + 1, val * 2 + 1);
}
int getMin(){
int x = 0;
int y = 0;
if(!q1.empty()){
x = q1.front();
}
if(!q2.empty()){
y = q2.front();
}
if(x == 0 || v[y] <= v[x]){
q2.pop();
return y;
}
q1.pop();
return x;
}
int main(){
int i;
in >> n;
v[0] = inf;
for(i = 1; i<=n; i++){
int nr;
in >> nr;
q1.push(i);
v[i] = nr;
}
while(q1.size() + q2.size() > 1){
int x = getMin();
int y = getMin();
q2.push(i);
v[i] = v[x] + v[y];
l[i] = x;
r[i] = y;
i++;
}
DFS(2*n-1, 0, 0);
out << rez << std::endl;
for(int i = 1; i<=n; i++){
out << sol[i].lungime << " " << sol[i].cod << std::endl;
}
}