Cod sursa(job #1239845)

Utilizator alex_bucevschiBucevschi Alexandru alex_bucevschi Data 9 octombrie 2014 21:13:01
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include <cstdio>
#include <vector>
#include <algorithm>
#define tip long long
using namespace std;
struct huffman
{
    huffman *l,*r;
    tip val;
    huffman()
    {
        l=r=NULL;
        val=1000000000000000010;
    }
}*huff,*x,*y,*a[2][10000000];
tip n,i,top1,top2,front1,front2,sol,q,aq,sc,lg;
bool poz,ok;
vector<pair<tip,tip>>v;
void run(huffman *nod)
{
    if(nod->l==NULL)
    {
        v.push_back(make_pair(lg,sc));
        return;
    }
    if(nod->l)
    {
        sc<<=1;
        lg++;
        run(nod->l);
        sc>>=1;lg--;
    }
    if(nod->r)
    {
        sc<<=1;
        sc++;
        lg++;
        run(nod->r);
        sc>>=1;lg--;
    }
}
int main()
{
    freopen("huffman.in","r",stdin);
    freopen("huffman.out","w",stdout);
    scanf("%lld",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%lld",&q);
        huff=new huffman;
        huff->val=q;
        a[0][i]=huff;
    }
    a[1][1]=new huffman;
    top1=n;
    front1=front2=top2=1;
    poz=1;
    while(top1-front1+top2-front2>=2)
    {
        if(a[poz][front2]==NULL)a[poz][front2]=new huffman;
        if(a[!poz][front1]==NULL)a[!poz][front1]=new huffman;
        if(a[poz][front2]->val<a[!poz][front1]->val)
            x=a[poz][front2++];
        else
            x=a[!poz][front1++];
         if(a[poz][front2]==NULL)a[poz][front2]=new huffman;
        if(a[!poz][front1]==NULL)a[!poz][front1]=new huffman;
        if(a[poz][front2]->val<a[!poz][front1]->val)
            y=a[poz][front2++];
        else
            y=a[!poz][front1++];
        huff=new huffman;
        sol+=x->val+y->val;
        huff->val=x->val+y->val;
        huff->l=x;
        huff->r=y;
        a[poz][top2++]=huff;
        if(top1<front1)
        {
            aq=top1;
            a[!poz][aq]=new huffman;
            poz=!poz;
            top1=top2;
            front1=front2;
            top2=front2=aq;
        }
    }
    printf("%lld\n",sol);
    run(huff);
    sort(v.begin(),v.end());
    for(vector<pair<tip,tip>>::iterator it=v.end()-1;it>=v.begin();it--)
        printf("%lld %lld\n",it->first,it->second);
    return 0;
}