Cod sursa(job #812421)

Utilizator danalex97Dan H Alexandru danalex97 Data 13 noiembrie 2012 20:55:18
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 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;
};

char Chr[Nmax];int Sz;

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]; long long Step;
        for ( Step = 1 ; Act.Dad ;Step <<= 1 , Act = A[Act.Dad] );
        for ( Act = A[i], Step >>= 1; Step ;Step >>= 1)
        {
            Chr[++Sz]= ( Act.Key == A[Act.Dad].Lson ? 0 : 1 );
            C[i] += Step * ( Act.Key == A[Act.Dad].Lson ? 0 : 1 );
            ++L[i];
            Act = A[Act.Dad];
        }
        Lung += V[i] * L[i];
    }

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