Cod sursa(job #2619435)

Utilizator AlexBosneag26Bosneag Alexandru AlexBosneag26 Data 27 mai 2020 17:43:15
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <queue>

using namespace std;

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

const int N = 1000001;

int lg[2*N], n, nr, st1 = 1, dr1 = 0, st2 = 1, dr2 = 0, st[2*N], dr[2*N];

queue <int> q1, q2;

long long cod[2*N], val[2*N];

void adauga(int x, int y)
{
    val[++nr] = val[x] + val[y];
    st[nr] = x;
    dr[nr] = y;
    q2.push(nr);
}


void preordine(int x)
{
    if (st[x] != 0)
    {
        cod[st[x]] = cod[x]*2;
        lg[st[x]] = 1 + lg[x];
        preordine(st[x]);
    }
    if (dr[x] != 0)
    {
        cod[dr[x]] = cod[x]*2 + 1;
        lg[dr[x]] = 1 + lg[x];
        preordine(dr[x]);
    }
}

int minim()
{
    int x;
    if (q2.empty())
    {
        x = q1.front();
        q1.pop();
    }
    else if (q1.empty() || val[q1.front()] >= val[q2.front()])
    {
        x = q2.front();
        q2.pop();
    }
    else
    {
        x = q1.front();
        q1.pop();
    }
    return x;
}

int main()
{

    in >> n;
    for(int i = 1, x; i <= n; i++)
    {
        in >> x;
        q1.push(i);
        val[i] = x;
    }
    nr = n;
    while(q1.size() + q2.size() > 1)
    {
        int x, y;

        if(q1.empty())
        {
            x = q2.front();
            q2.pop();
            y = q2.front();
            q2.pop();
        }
        else if(q2.empty())
        {
            x = q1.front();
            q1.pop();
            y = q1.front();
            q1.pop();
        }
        else
        {
            x = minim();
            y = minim();
        }
        adauga(x, y);
    }
    long long sum = 0;
    for(int i = n+1; i <= nr; i++)
        sum += val[i];
    out << sum << "\n";

    cod[nr] = 0;
    preordine(nr);

    for(int i = 1; i <= n; i++)
    {
        out << lg[i] << " " << cod[i] << "\n";
    }
    return 0;
}