Cod sursa(job #461308)

Utilizator BitOneSAlexandru BitOne Data 6 iunie 2010 12:05:48
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <map>
#include <cstdlib>
#include <fstream>
#define Nmax 2000011
#define oo 1000000000

/*
 *
 */
using namespace std;
typedef pair< int, int > pr;
struct tree
{
    int Cost;
    int left, right;
    tree( void ) : Cost(oo), left(0), right(0) {}
} t[Nmax];
multimap< int, int > v;
ofstream out( "huffman.out" );
inline void output( int x, int cod, int idx )
{
    if( 0 == t[x].left*t[x].right ) //nod terminal => nod din sir
    {
        out<<idx<<' '<<cod<<'\n';
    }
    else {
                output( t[x].left, cod, idx+1 );
                output( t[x].right, cod+(1<<idx), idx+1 );
         }
}
int main( void )
{
    pr x, y;
    int N, i, j, s=0;
    ifstream in( "huffman.in" );
    in>>N;
    for( i=1; i <= N; ++i )
    {
        in>>j;
        v.insert( pr( j, i ) );
    }
    while( v.size() > 1 )
    {
        x=*(v.begin());
        v.erase(v.begin());
        y=*(v.begin());
        v.erase(v.begin());
        t[x.second].Cost=x.first;       t[y.second].Cost=y.first;
        s+=( t[i].Cost=x.first+y.first );
        t[i].left=x.second; t[i].right=y.second;
        v.insert( pr( t[i].Cost, i ) );
        ++i;
    }
    out<<s<<'\n';
    output( i-1, 0, 0 );
    return EXIT_SUCCESS;
}