Cod sursa(job #2623421)

Utilizator roxana1708Roxana Gherghina roxana1708 Data 3 iunie 2020 10:17:51
Problema Coduri Huffman Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>

#define max 1000001
#define inf 1LL * 1000000000 * 1000000000

struct Nod {
    long long v;
    long f[2];
} nod[2*max];

long q[2][max], cod_b10[max];
long long  m, sol, biti[max];
long n, nod_curr, p, indiceParcurgere[2], nodUltim[2], i, j;


void coduri(long poz, long long cod, long 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;
}