Cod sursa(job #826491)

Utilizator tzipleatudTudor Tiplea tzipleatud Data 30 noiembrie 2012 20:05:01
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#define NM 1000010
#define INF 999999999999999

using namespace std;

ifstream f("huffman.in");
ofstream g("huffman.out");

struct NodeType
{
    int Sons[2];
    long long V;
};

NodeType Node[NM];
int N,K;
int i,j;
int Length[NM];
int Front[2],Back[2];
int Q[2][NM];
long long Val[NM];
long long ANS;
int son,cson;

void DF (int CNode, int Level, long long Code)
{
    if (Node[CNode].Sons[0]==0 || Node[CNode].Sons[1]==0)
    {
        Length[CNode]=Level;
        Val[CNode]=Code;

        return;
    }

    DF(Node[CNode].Sons[0], Level+1, 2LL*Code);
    DF(Node[CNode].Sons[1], Level+1, 2LL*Code+1);
}

int main ()
{
    f >> N;

    Front[0]=Front[1]=1;
    Back[0]=N;
    K=N;

    for (i=1; i<=N; i++)
    {
        f >> Node[i].V;
        Q[0][i]=i;
    }

    long long CVAL;
    int P;

    while (Front[0]+Front[1]<=Back[0]+Back[1])
    {
        ++K;

        for (son=0; son<2; son++)
        {
            CVAL=INF;
            P=0;

            for (cson=0; cson<2; cson++)
                if (Node[Q[cson][Front[cson]]].V<CVAL && Front[cson]<=Back[cson])
                {
                    CVAL=Node[Q[cson][Front[cson]]].V;
                    P=cson;
                }

            Node[K].Sons[son]=Q[P][Front[P]];
            Node[K].V+=Node[Q[P][Front[P]]].V;
            Front[P]++;
        }

        ANS+=Node[K].V;
        Q[1][++Back[1]]=K;
    }

    DF(K,0,0);

    g << ANS << '\n';

    for (i=1; i<=N; i++)
        g << Length[i] << ' ' << Val[i] << '\n';

    f.close();
    g.close();

    return 0;
}