Pagini recente » Cod sursa (job #582473) | Cod sursa (job #1590245) | Cod sursa (job #2974934) | Cod sursa (job #2862727) | Cod sursa (job #2623427)
#include <iostream>
#include <fstream>
#define max 1000001
#define inf 1LL * 1000000000 * 1000000000
struct Nod {
long long int v;
long int f[2];
} nod[2*max];
long int q[2][max], biti[max];
long long int m, sol, cod_b10[max];
long int n, nod_curr, p, indiceParcurgere[2], nodUltim[2], i, j;
void coduri(long int poz, long long int cod, long int nivel) {
if(nod[poz].f[0]) {
coduri(nod[poz].f[0], cod*2, nivel+1);
coduri(nod[poz].f[1], cod*2+1, nivel+1);
return;
}
biti[poz] = nivel;
cod_b10[poz] = cod;
}
void build() {
nod_curr = n;
indiceParcurgere[0] = indiceParcurgere[1] = 1;
nodUltim[0] = n;
while(indiceParcurgere[0] + indiceParcurgere[1] <= nodUltim[0] + nodUltim[1]) {
nod_curr++;
for(j = 0; j < 2; j++) {
p = 0;
m = inf;
for(i = 0; i < 2; i++) {
if(nod[q[i][indiceParcurgere[i]]].v < m && indiceParcurgere[i] <= nodUltim[i]) {
p = i;
m = nod[q[i][indiceParcurgere[i]]].v;
}
}
nod[nod_curr].f[j] = q[p][indiceParcurgere[p]];
nod[nod_curr].v += nod[q[p][indiceParcurgere[p]]].v;
indiceParcurgere[p]++;
}
nodUltim[1]++;
q[1][nodUltim[1]] = nod_curr;
sol += nod[nod_curr].v;
}
coduri(nod_curr, 0, 0);
}
int main() {
std::ifstream f("huffman.in");
std::ofstream g("huffman.out");
f >> n;
for(i = 1; i <= n; i++) {
f >> nod[i].v;
q[0][i] = i;
}
build();
g << sol << "\n";
for(i = 1; i <= n; i++) {
g << biti[i] << " " << cod_b10[i] << "\n";
}
return 0;
}