Cod sursa(job #812410)

Utilizator danalex97Dan H Alexandru danalex97 Data 13 noiembrie 2012 20:37:19
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <queue>
using namespace std;

const int Nmax = 1000010;
const int Smax = 2000010;

int N,V[Nmax];
long long C[Nmax];
int L[Nmax],Lung;

struct Huffman
{
    int Val , Key;
    int Lson, Rson , Dad;
};

Huffman A[Smax];
int Size;

#define val first
#define key second
typedef pair<int,int> Pair;

priority_queue< Pair , vector<Pair> , greater<Pair> > MinH;

ifstream F("huffman.in");
ofstream G("huffman.out");

int main()
{
    F>>N, Size = N;
    for (int i=1;i<=N;++i)
    {
        F>>V[i];
        A[i].Key = i;
        A[i].Val = V[i];
        A[i].Lson = 0;
        A[i].Rson = 0;
        MinH.push( make_pair( V[i] , i ) );
    }

    while ( MinH.size() > 1 )
    {
        Pair P1 = MinH.top(); MinH.pop();
        Pair P2 = MinH.top(); MinH.pop();
        Pair P3 = make_pair( P1.val + P2.val , ++Size );
        MinH.push( P3 );

        A[Size].Key = P3.key;
        A[Size].Val = P3.val;
        A[Size].Lson = P1.key;
        A[Size].Rson = P2.key;

        A[P1.key].Dad = A[Size].Key;
        A[P2.key].Dad = A[Size].Key;
    }

    for (int i=1;i<=N;++i)
    {
        Huffman Act = A[i];
        C[i]=1;
        while ( Act.Dad )
        {
            C[i]*=2;
            C[i] += ( Act.Key == A[Act.Dad].Lson ) ? 0 : 1;
            ++L[i];
            Act = A[Act.Dad];
        }
        C[i]>>=1;
        Lung += V[i] * L[i];
    }

    G<<Lung<<'\n';
    for (int i=1;i<=N;++i)
        G<<L[i]<<' '<<C[i]<<'\n';
}