Cod sursa(job #2504999)

Utilizator Alex_BubBuburuzan Alexandru Alex_Bub Data 5 decembrie 2019 22:44:01
Problema Coduri Huffman Scor 70
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <queue>

using namespace std;

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

const int NMax = 2e6;

long long N, Sol, Son[NMax + 5][2], ct, Ap[NMax + 5], L[NMax + 5], Ans[NMax + 5];
queue <long long> Q1, Q2;

long long GetMin()
{
    long long x;

    if(Q1.empty())
    {
        x = Q2.front(), Q2.pop();
        return x;
    }

    if(Q2.empty())
    {
        x = Q1.front(), Q1.pop();
        return x;
    }

    if(Ap[Q1.front()] <= Ap[Q2.front()])
    {
        x = Q1.front(), Q1.pop();
        return x;
    }
    else
    {
        x = Q2.front(), Q2.pop();
        return x;
    }
}

void DFS(int Nod, long long Val, int l)
{
    if(!Son[Nod][0])
    {
        L[Nod] = l, Ans[Nod] = Val;
        return;
    }
    for(int t = 0; t < 2; t++)
        DFS(Son[Nod][t], (Val << 1LL) + t, l + 1);
}

int main()
{
    fin >> N; ct = N;

    for(int i = 1; i <= N; i++)
        fin >> Ap[i], Q1.push(i);

    while((Q1.size() + Q2.size()) != 1)
    {
        long long x = GetMin(), y = GetMin();
        Q2.push(++ct);

        Ap[ct] = Ap[x] + Ap[y];
        Sol += Ap[ct];
        Son[ct][0] = x, Son[ct][1] = y;
    }
    fout << Sol << '\n';
    DFS(ct, 0, 0);

    for(int i = 1; i <= N; i++)
        fout << L[i] << " " << Ans[i] << '\n';

    fin.close();
    fout.close();

    return 0;
}