Cod sursa(job #791986)

Utilizator visanrVisan Radu visanr Data 26 septembrie 2012 00:41:38
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
using namespace std;

#define nmax 1000010

char s[100];
int N, node, crtNode, V[nmax], Q[2][nmax], beg[2], end[2];
int son[2 * nmax][2], lg[nmax];
long long B[nmax], ans, now[2 * nmax];


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);
    }
    lg[node] = length;
    B[node] = val;
}

int main()
{
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);
    int i, j;
    fgets(s, 100, stdin);
    for(i = 0; isdigit(s[i]); i++)
        N = N * 10 + s[i] - '0';
    beg[0] = 1;
    end[0] = 0;
    for(i = 1; i <= N; i++)
    {
        fgets(s, 100, stdin);
        for(j = 0; isdigit(s[j]); j++)
            V[i] = V[i] * 10 + s[j] - '0';
        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;
}