Cod sursa(job #792100)

Utilizator visanrVisan Radu visanr Data 26 septembrie 2012 15:00:14
Problema Coduri Huffman Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <cstdio>
#include <fstream>
#include <cctype>
using namespace std;

#define nmax 1000010

ifstream in("huffman.in");
char s[1 << 18];
int N, node, crtNode, V[nmax], Q[2][nmax], beg[2], end[2], nowpos;
int son[2 * nmax][2], lg[nmax];
long long B[nmax], ans, now[2 * nmax];

void verify()
{
    if(s[nowpos] == 0)
    {
        in.get(s, 1 << 18, '\0');
        nowpos = 0;
    }
}

int get()
{
    int nr = 0;
    while(!isdigit(s[nowpos]))
        nowpos ++, verify();
    while(isdigit(s[nowpos]))
        nr = nr * 10 + s[nowpos] - '0', nowpos ++, verify();
    return nr;
}

void DFS(int node, long long val, int length)
{
    if(son[node][0])
    {
        DFS(son[node][0], val * 2, length + 1);
        DFS(son[node][1], val * 2 + 1, length + 1);
        return ;
    }
    lg[node] = length;
    B[node] = val;
}

int main()
{
    freopen("huffman.out", "w", stdout);
    int i, j;
    verify();
    N = get();
    beg[0] = 1;
    end[0] = 0;
    for(i = 1; i <= N; i++)
    {
        V[i] = get();
        Q[0][++end[0]] = i;
        now[i] = V[i];
    }
    crtNode = N;
    beg[1] = 1;
    end[1] = 0;
    int pos, crt;
    while(end[0] + end[1] >= beg[0] + beg[1])
    {
        crtNode ++;
        for(i = 0; i < 2; i++)
        {
            pos = -1;
            for(j = 0; j < 2; j++)
                if(beg[j] <= end[j] && (pos == -1 || now[pos] > now[Q[j][beg[j]]]))
                {
                    pos = Q[j][beg[j]];
                    crt = j;
                }
            beg[crt] ++;
            now[crtNode] += now[pos];
            son[crtNode][i] = pos;
        }
        Q[1][++end[1]] = crtNode;
    }
    DFS(crtNode, 0, 0);
    for(i = 1; i <= N; i++)
        ans += 1LL * now[i] * lg[i];
    printf("%lld\n", ans);
    for(i = 1; i <= N; i++)
    {
        printf("%i %lld\n", lg[i], B[i]);
    }
    return 0;
}