Cod sursa(job #2908528)

Utilizator tiut_cristianTiut Cristian tiut_cristian Data 4 iunie 2022 10:10:43
Problema Coduri Huffman Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;

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

queue<int> before, after;
int n, m;

long long val[1000005];
int st[1000005], dr[1000005];
pair<long long, long long> ans[1000005];
long long sum;

void citire()
{
    fin >> n;
    m = n;
    for(int i = 1; i <= n; i++)
    {
        int x;
        fin >> x;
        val[i] = x;
        before.push(i);
    }
}

void dfs(int nod, long long depth, long long nr)
{
    if(!st[nod] && !dr[nod])
    {   ans[nod].first = depth;
        ans[nod].second = nr;
        return;
    }
    sum += val[nod];
    dfs(st[nod], depth + 1, nr * 2);
    dfs(dr[nod], depth + 1, nr * 2 + 1);
}

void adauga_nod(int x, int y)
{   val[++n] = val[x] + val[y];
    st[n] = x;
    dr[n] = y;
    after.push(n);
}

int minx()
{
    int nr;
    if (!before.empty())
    {
        if (!after.empty())
        {
            if (val[before.front()] < val[after.front()])
            {
                nr = before.front();
                before.pop();
            }
            else
            {
                nr = after.front();
                after.pop();
            }
        }
        else
        {
            nr = before.front();
            before.pop();
        }
    }
    else
    {
        nr = after.front();
        after.pop();
    }
    return nr;
}

void afisare()
{
    fout << sum << '\n';
    for(int i = 1; i <= m; ++i)
        fout << ans[i].first << ' ' << ans[i].second << '\n';
}

int main()
{
    citire();
    while(before.size() + after.size() > 1)
    {
        int x = minx(), y = minx();
        adauga_nod(x, y);
    }
    dfs(n, 0, 0);
    afisare();

    return 0;
}