Cod sursa(job #2500693)

Utilizator mirceaisherebina mircea mirceaishere Data 28 noiembrie 2019 15:40:18
Problema Coduri Huffman Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");

long long code[2000010], sol, f[2000010], st[1000010], dr[1000010], niv[2000010];
long long n, i, j, aux, s1, s2, s3;

void dfs(long long nod, long long nivel, long long cod){
    niv[nod]=nivel;
    code[nod]=cod;
    if(st[nod]){
        dfs(st[nod], nivel+1, 1LL*cod*2);
    }
    if(dr[nod]){
        dfs(dr[nod], nivel+1, 1LL*cod*2+1);
    }
}


int main(){
    fin>>n;
    for(i=1; i<=n; i++){
        fin>>f[i];
        f[n+i]=200000010;
    }
    i=1;
    j=n+1;

    for(aux=n+1; aux<2*n; aux++){
        /// la fiecare pas luam suma celor mai mici 2 numere si o punem in arbore
        if(i+1>n){
            s1=200000010;
        }else{
            s1=f[i]+f[i+1];
        }
        if(j>aux || i>n){
            s2=200000010;
        }else{
            s2=f[i]+f[j];
        }
        if(j+1>aux){
            s3=200000010;
        }else{
            s3=f[j]+f[j+1];
        }

        if(s1<=s2 && s1<=s3){
            st[aux]=i;
            dr[aux]=i+1;
            f[aux]=s1;
            i+=2;
        }else{
            if(s2<=s1 && s2<=s3){
                st[aux]=i;
                dr[aux]=j;
                f[aux]=s2;
                i++;
                j++;
            }else{
                /// s3 este cea mai mica
                st[aux]=j;
                dr[aux]=j+1;
                f[aux]=s3;
                j+=2;
            }
        }
    }
    dfs(2*n-1, 0, 0);
    for(aux=1; aux<=n; aux++){
        sol+=1LL*niv[aux]*f[aux];
    }
    fout<<sol<<"\n";
    for(i=1; i<=n; i++){
        fout<<niv[i]<<" "<<code[i]<<"\n";
    }
}