Cod sursa(job #2375807)

Utilizator dacianouaPapadia Mortala dacianoua Data 8 martie 2019 12:22:14
Problema Coduri Huffman Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <queue>
#include <bitset>
#define nmax 1000000
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
int n,t[(nmax<<1)+5],lung[(nmax<<1)+5],nrnoduri,s,cod[nmax+5];
long long v[(nmax<<1)+5];
bitset<(nmax<<1)+5> decarefiu;
queue<long long> q1,q2;
long long huffman()
{
    long long aux;
    if(!q1.empty() && !q2.empty())
    {
        if(v[q1.front()]<v[q2.front()])
        {
            aux=q1.front();
            q1.pop();
            return aux;
        }
        else
        {
            aux=q2.front();
            q2.pop();
            return aux;
        }
    }
    else if(!q1.empty())
    {
        aux=q1.front();
        q1.pop();
        return aux;
    }
    else if(!q2.empty())
    {
        aux=q2.front();
        q2.pop();
        return aux;
    }
    return -1;
}
int main()
{
    fin>>n;
    int x,y;
    int nrnoduri=n;
    for(int i=1;i<=n;i++)
    fin>>v[i],q1.push(i);
    while(1)
    {
        x=huffman();
        y=huffman();
        if(y!=-1)
        {
            ++nrnoduri;
            v[nrnoduri]=v[x]+v[y],q2.push(nrnoduri);
            t[x]=t[y]=nrnoduri;
            decarefiu[x]=0;
            decarefiu[y]=1;
        }
        else break;
    }
    for(int i=n+1;i<=nrnoduri;i++)
        s+=v[i];
    fout<<s<<"\n";
    for(int i=1;i<=n;i++)
    {
        x=i;
        y=0;
        while(t[x]!=0)
        {
            lung[i]++;
            cod[lung[i]]=decarefiu[x];
            x=t[x];
        }
        for(int j=lung[i];j>=1;j--)
            y=y*2+cod[j];
        fout<<lung[i]<<" "<<y<<"\n";
    }
    return 0;
}