Cod sursa(job #2581084)

Utilizator Rares31100Popa Rares Rares31100 Data 14 martie 2020 15:10:58
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
#define ULL unsigned long long

using namespace std;

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

int n;
int coadaP[1000001],lastP=1,vfP,sizeP;
int coadaC[1000001],lastC=1,vfC,sizeC;
ULL val[2000001];
int urm[2000001];
bool muchie[2000001];
ULL Ltot;

int minim()
{
    if(!sizeC)
    {
        sizeP--;
        return coadaP[lastP++];
    }
    else if(!sizeP)
    {
        sizeC--;
        return coadaC[lastC++];
    }
    else if(val[ coadaP[lastP] ]<=val[ coadaC[lastC] ])
    {
        sizeP--;
        return coadaP[lastP++];
    }
    else
    {
        sizeC--;
        return coadaC[lastC++];
    }
}

int main()
{
    in>>n;

    for(int i=1;i<=n;i++)
    {
        in>>val[i];
        coadaP[++vfP]=i;
    }
    sizeP=n;

    int i,j,poz=n+1;
    while(sizeP+sizeC>=2)
    {
        i=minim();
        j=minim();

        urm[i]=poz;
        urm[j]=poz;
        muchie[j]=1;
        val[poz]=val[i]+val[j];

        coadaC[++vfC]=poz;
        sizeC++;

        Ltot+=val[poz];
        poz++;
    }

    out<<Ltot<<'\n';

    ULL nr;
    int lung;

    for(int i=1;i<=n;i++)
    {
        nr=0,lung=0;
        poz=i;

        while(urm[poz])
        {
            nr+=(ULL)muchie[poz]<<lung;
            lung++;
            poz=urm[poz];
        }

        out<<lung<<' '<<nr<<'\n';
    }

    return 0;
}