Cod sursa(job #2981591)

Utilizator Elvis_CostinTuca Elvis-Costin Elvis_Costin Data 18 februarie 2023 11:52:47
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string np = "huffman";
ifstream f(np + ".in");
ofstream g(np + ".out");

// #define f cin
// #define g cout

int n, n2, st[2000003], dr[2000003];
ll rez, v[2000003], w1[1000003], w2[1000003];
queue<int> q1, q2;

int getnew()
{
    int rez;
    if (q1.empty())
        rez = q2.front(), q2.pop();
    else if (q2.empty())
        rez = q1.front(), q1.pop();
    else if (v[q1.front()] < v[q2.front()])
        rez = q1.front(), q1.pop();
    else
        rez = q2.front(), q2.pop();
    return rez;
}
void dfs(int nod, ll nr, int k)
{
    if (!st[nod] and !dr[nod])
        rez += 1ll * v[nod] * k,
            w1[nod] = k, w2[nod] = nr;
    else
        dfs(st[nod], nr * 2, k + 1),
            dfs(dr[nod], nr * 2 + 1, k + 1);
}
int main()
{
    f >> n;
    n2 = n;
    for (int i = 1; i <= n; i++)
        f >> v[i], q1.push(i);

    if (n == 1)
        g << v[1] << "\n1 1", exit(0);

    int aux1 = q1.front();
    q1.pop();
    int aux2 = q1.front();
    q1.pop();
    v[++n2] = v[aux1] + v[aux2];
    st[n2] = aux1, dr[n2] = aux2;
    q2.push(n2);
    while (q1.size() + q2.size() > 1)
    {
        aux1 = getnew();
        aux2 = getnew();
        v[++n2] = v[aux1] + v[aux2];
        st[n2] = aux1;
        dr[n2] = aux2;
        q2.push(n2);
    }

    dfs(n2, 0, 0);

    g << rez << '\n';
    for (int i = 1; i <= n; i++)
        g << w1[i] << " " << w2[i] << '\n';

    return 0;
}