Cod sursa(job #2517680)

Utilizator Rares31100Popa Rares Rares31100 Data 3 ianuarie 2020 22:43:47
Problema Coduri Huffman Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
#define Val first
#define Poz second
#define PII pair<int,int>
#define LL long long

using namespace std;

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

int n,vf;
priority_queue <PII,vector<PII>,greater<PII>> c;

LL val[2000001];
int tata[2000001];
PII fii[2000001];
int sizeNr[2000001];
LL nr[2000001];

int main()
{
    in>>n;
    vf=n;

    for(int i=1;i<=n;i++)
    {
        in>>val[i];
        c.push({val[i],i});
    }

    PII nod1,nod2;
    while(!c.empty())
    {
         nod1=c.top();c.pop();
         nod2=c.top();c.pop();

         val[++vf]=nod1.Val+nod2.Val;
         fii[vf]={nod1.Poz,nod2.Poz};
         tata[nod1.Poz]=vf;
         tata[nod2.Poz]=vf;

         if(!c.empty())
            c.push({val[vf],vf});
    }

    LL sol=0;

    bool cod[60];
    int vfc=0;
    for(int i=1;i<=n;i++)
    {
        int poz=i,pozAnt=i;

        while(tata[poz])
        {
            poz=tata[poz];

            if(pozAnt==fii[poz].first)
                cod[++vfc]=0;
            else
                cod[++vfc]=1;

            pozAnt=poz;
        }

        sol+=vfc*val[i];
        sizeNr[i]=vfc;

        for(int j=0;j<vfc;j++)
            if(cod[ j+1 ]==1)
                nr[i]+=(1<<j);
    }

    out<<sol<<'\n';

    for(int i=1;i<=n;i++)
        out<<sizeNr[i]<<' '<<nr[i]<<'\n';

    return 0;
}