Cod sursa(job #1290933)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 11 decembrie 2014 22:56:37
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <queue>
using namespace std;

ifstream is("huffman.in");
ofstream os("huffman.out");

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()
{
    is >> N; indexOfQx = N + 1;

    for  ( int i = 1; i <= N; ++i )
    {
        is >> 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);

    os << Sol << '\n';
    for ( int i = 1; i <= N; ++i )
        os << sol[i].first << ' ' << sol[i].second << '\n';

    is.close();
    os.close();
}

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;
}