Cod sursa(job #1397183)

Utilizator SmarandaMaria Pandele Smaranda Data 23 martie 2015 12:28:28
Problema Coduri Huffman Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 kb
#include <cstdio>
#include <utility>
#include <fstream>
#include <vector>

using namespace std;

const int N = 1000008;

long long a [N], b [N], sol [N];
int nodb [N], lg [N], n, st [100];

int graph1 [2 * N + 4], graph2 [2 * N + 4];

void dfs (int x, int level) {
    int i, bit;

    if (x <= n) {
        lg [x] = level + 1;
        sol [x] = 0;
        for (i = level, bit = 0; i >= 0; i --, bit ++)
            if (st [i])
                sol [x] = sol [x] | (1ll << bit);
        return ;
    }
    st [level + 1] = 0;
    dfs (graph1 [x], level + 1);
    st [level + 1] = 1;
    dfs (graph2 [x], level + 1);
}

int main () {
    int i, u, i1, i2, poz, l;
    long long  k, ans = 0;

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

   // fin >> n;
   scanf ("%d", &n);
    for (i = 1; i <= n; i ++)
        scanf ("%lld", &a [i]);
       //fin >> a [i];

    l = n;
    b [1] = a [1] + a [2];
    ans = ans + b [1];
    nodb [1] = ++ l;
    graph1 [l] = 1;
    graph2 [l] = 2;
    i1 = 3;
    i2 = u = 1;
    while (i1 <= n || i2 <= u) {
        for (i = 1; i <= 2; i ++) {
            k = (1ll << 62) - 1;
            poz = -1;
            if (i1 <= n && a [i1] < k) {
                k = a [i1];
                poz = 1;
            }
            if (i2 <= u && b [i2] < k) {
                k = b [i2];
                poz = 2;
            }
            if (poz != -1) {
                b [u + 1] = b [u + 1] + k;
                nodb [u + 1] = l + 1;
                if (poz == 1) {
                    if (i == 1)
                        graph1 [l + 1] = i1;
                    else graph2 [l + 1] = i1;
                    ++ i1;
                }
                if (poz == 2) {
                    if (i == 1)
                        graph1 [l + 1] = nodb [i2];
                    else graph2 [l + 1] = nodb [i2];
                    ++ i2;
                }
            }
        }
        if (poz == -1) {
            break;
        }
        ++ u; ++ l;
        ans = ans + b [u];
    }
    printf ("%lld\n", ans);
    dfs (nodb [u], -1);
    for (i = 1; i <= n; i ++)
        printf ("%d %lld\n", lg [i], sol [i]);
    return 0;
}