Cod sursa(job #1087759)

Utilizator ioalexno1Alexandru Bunget ioalexno1 Data 19 ianuarie 2014 20:27:23
Problema Coduri Huffman Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <map>


using namespace std;

const int MAX_N = 1000010;
int N, nr, lg[MAX_N];
long long a[MAX_N], ans;
multimap <long long, int> M;
multimap <long long, int>::iterator it, aux;

struct nod{

    int st, dr;
    long long val;
}nod[2 * MAX_N];

void constr(){

    nr = N;
    while( M.size() > 1 ){

        it = M.begin();
        aux = it; ++aux;
        ++nr;
        nod[nr].val = it->first + aux->first;
        nod[nr].st = it->second;
        nod[nr].dr = aux->second;
        M.erase( it );
        M.erase( aux );
        M.insert( pair<long long, int>( nod[nr].val, nr ) );
        ans += nr[nod].val;
    }

}

void df( int ind, long long cod, int niv ){

    if( nod[ind].st ){

        df( nod[ind].st, cod * 2, niv + 1 );
        df( nod[ind].dr, cod * 2 + 1, niv + 1 );
    }
    lg[ind] = niv;
    a[ind] = cod;
}

int main()
{
    ifstream cin( "huffman.in" );

    cin >> N;
    for( int i = 1; i <= N; ++i ){

        cin >> nod[i].val;
        M.insert( pair< long long, int >( nod[i].val, i ) );
    }


    cin.close();

    constr();
    df( nr, 0, 0 );

    ofstream cout( "huffman.out" );

    cout << ans << "\n";
    for( int i = 1; i <= N; ++i )
        cout << lg[i] << " " << a[i] << "\n";

    cout.close();

    return 0;
}