Cod sursa(job #2197704)

Utilizator EuAlexOtaku Hikikomori EuAlex Data 22 aprilie 2018 18:45:43
Problema Coduri Huffman Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include <iostream>
#include <climits>
#include <vector>
#include <cstdio>

using namespace std;

//ifstream in("huffman.in");
//ofstream out("huffman.out");

int const nmax = 1e6;

int q[2][1 + nmax], le[2], ri[2];
long long sol[2][1 + nmax];

struct Node {
    int freq;
    int sons[2];
};

Node v[1 + 2 * nmax];

long long suma;

void dfs(int nod, int h = 0, long long code = 0) {
    if(v[nod].sons[0] + v[nod].sons[1] > 0) {
        dfs(v[nod].sons[0], h + 1, code * 2);
        dfs(v[nod].sons[1], h + 1, code * 2 + 1);
    } else {
        suma += 1LL * h * v[nod].freq;
        sol[0][nod] = h;
        sol[1][nod] = code;
    }
}

int main() {
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);

    int n;
    scanf("%d", &n);

    for(int i = 1; i <= n; ++ i) {
        //in >> v[i].freq;
        scanf("%d", &v[i].freq);
        q[0][i] = i;
    }

    le[0] = le[1] = 1;
    ri[0] = n;
    ri[1] = 0;

    int nnod = n;
    while(le[0] <= ri[0] || le[1] < ri[1]) {
        nnod ++;
        for(int i = 0; i < 2; i++) {
            int minf = INT_MAX, unde = 0;
            for(int j = 0; j < 2; j++) {
                if(le[j] <= ri[j] && v[q[j][le[j]]].freq < minf) {
                    minf = v[q[j][le[j]]].freq;
                    unde = j;
                }
            }
            v[nnod].freq += minf;
            v[nnod].sons[i] = q[unde][le[unde] ++];
        }
        q[1][++ ri[1]] = nnod;
    }

    dfs(nnod);

    printf("%lld\n", suma);

    for(int i = 1; i <= n; ++ i) {
        //out << sol[0][i] << " " << sol[1][i] << '\n';
        printf("%lld %lld\n", sol[0][i], sol[1][i]);
    }

    return 0;
}