Cod sursa(job #1290935)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 11 decembrie 2014 23:01:02
Problema Coduri Huffman Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <cstdio>
#include <queue>
using namespace std;

int N, Fr[1000001],  indexOfQx;
long long Sol;
pair <int , long long > sol[2*1000001];
queue <int> Q, Qx;

struct Node {
    long long value;
    int index;
    int son[2];
};

Node Arb[2 * 1000001];

inline int getMin();
void DFS(Node node, long long res, int level)
{
    if ( node.son[0] )
    {
        DFS(Arb[node.son[0]], res * 2, level + 1);
        DFS(Arb[node.son[1]], res * 2 + 1, level + 1);
    }
    else
    {
        sol[node.index] = make_pair(level,res);
        Sol += level * Fr[node.index];
    }
}

int main()
{
    freopen("huffman.in","r",stdin);
    freopen("huffman.out","w",stdout);
    scanf("%i",&N);
    indexOfQx = N + 1;

    for  ( int i = 1; i <= N; ++i )
    {
        scanf("%i",&Fr[i]);
        Arb[i].value = Fr[i];
        Arb[i].index = i;
        Q.push(i);
    }

    Node aux, aux1, aux2;

    for ( ; !Q.empty() || Qx.size() > 1; )
    {
        aux1 = Arb[getMin()];
        aux2 = Arb[getMin()];
        aux.value = aux1.value + aux2.value;
        aux.son[0] = aux1.index;
        aux.son[1] = aux2.index;
        aux.index = indexOfQx;
        Arb[aux.index] = aux;
        indexOfQx++;

        Qx.push(aux.index);
    }

    DFS(aux,0,0);

    printf("%i\n",Sol);
    for ( int i = 1; i <= N; ++i )
        printf("%i %lli\n",sol[i].first,sol[i].second);
}

inline int getMin()
{
    int index;

    if ( Q.empty() )
    {
        index = Qx.front();
        Qx.pop();
    }
    else if ( Qx.empty() )
    {
        index = Q.front();
        Q.pop();
    }
    else if ( Arb[Q.front()].value < Arb[Qx.front()].value )
    {
        index = Q.front();
        Q.pop();
    }
    else
    {
        index = Qx.front();
        Qx.pop();
    }

    return index;
}