Cod sursa(job #1831492)

Utilizator andreiudilaUdila Andrei andreiudila Data 18 decembrie 2016 11:03:16
Problema Coduri Huffman Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <stdio.h>
using namespace std;/*
ifstream cin("huffman.in");
ofstream cout("huffman.out");*/

long long n,i,l,r,idx,cx,cy;
long long f[1000002],faux[1000002];
int fr[1000002];
long long solv[1000002];

int soll[1000002];

struct nod
{
    int idx;
    nod *l;
    nod *r;
}*a[1000002], *x,*y, *aux[1000002],*p, *root;

void dfs(nod *root, long long l, long long v)
{
    if(root->l==NULL && root->r==NULL)
    {
        soll[root->idx]=l;
        solv[root->idx]=v;
    }
    else
    {
        if(root->l!=NULL) dfs(root->l, l+1, (long long)2*v);
        if(root->r!=NULL) dfs(root->r, l+1, (long long)2*v+(long long)1);
    }
}

int main()
{
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);
    //cin>>n;
    scanf("%d", &n);
    for(i=1; i<=n; ++i)
    {
       // cin>>f[i];
       scanf("%lld", &f[i]);
        fr[i]=f[i];
    }

    f[n+1]=(long long)1000000000*(long long)1000000000;

    for(i=1; i<=n; ++i)
    {
        a[i]=new nod;
        a[i]->l=NULL;
        a[i]->r=NULL;
        a[i]->idx=i;
    }

    l=1;
    r=0;
    idx=1;

    while(n-idx+1+r-l+1>1)
    {
        if(l<=r && faux[l]<f[idx])
        {
            --idx;
            f[idx]=faux[l];
            a[idx]=aux[l];
            ++l;
        }

        x=a[idx];
        cx=f[idx];
        ++idx;

        if(l<=r && faux[l]<f[idx])
        {
            --idx;
            f[idx]=faux[l];
            a[idx]=aux[l];
            ++l;
        }

        y=a[idx];
        cy=f[idx];
        ++idx;

        p=new nod;
        p->l=x;
        p->r=y;

        ++r;
        faux[r]=cx+cy;
        aux[r]=p;

        root=p;

    }

    dfs(root,0,0);

    long long suma=0;

    for(i=1; i<=n; ++i)
        suma+=(long long)fr[i]*soll[i];

    //cout<<suma<<"\n";
    printf("%lld\n", suma);

    for(i=1; i<=n; ++i)
        //cout<<soll[i]<<" "<<solv[i]<<"\n";
            printf("%d %lld\n", soll[i],solv[i]);
    return 0;
}