Cod sursa(job #1241510)

Utilizator alex_bucevschiBucevschi Alexandru alex_bucevschi Data 13 octombrie 2014 18:09:49
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#define tip long long
#define N 2000010
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
tip n,i,val[N],tata[N],top1,top2,front1,front2,poz1,poz2,sol,lg,bit,vl,x;
inline tip select()
{
    if(top1<front1)
    {
        top1=top2;
        front1=front2;
        front2=top1+1;
    }
    if(top2<front2)
        return front1++;
    return val[front1]<=val[front2]?front1++:front2++;
}
int main()
{
    fin.sync_with_stdio(0);
    fin>>n;
    for(i=1;i<=n;i++)
       fin>>val[i];
    top1=top2=n;
    front1=1;
    front2=top2+1;
    for(i=n+1;i<2*n;i++)
    {
        poz1=select();
        poz2=select();
         x=(++top2)<<1;
        tata[poz1]=x;
        tata[poz2]=x+1;
        val[top2]=val[poz1]+val[poz2];
        sol+=val[top2];
    }
    fout<<sol<<'\n';
    for(i=1;i<=n;i++)
    {
        vl=bit=0;
        lg=-1;
        x=i;
        while(x)
        {
            lg++;
            vl=((tata[x]&1)<<bit)+vl;
            bit++;
            x=tata[x]>>1;
        }
       fout<<lg<<' '<<vl<<'\n';
    }
    return 0;
}