Cod sursa(job #2919197)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 16 august 2022 13:57:59
Problema Coduri Huffman Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <queue>

using namespace std;

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

const int maxN = 1000005;
const long long inf = (1LL << 60);
int n, depth[maxN];
long long len, ans[maxN];
struct ura {
    long long val;
    int nod, st, dr;
}v[2 * maxN];
queue <int> q[2];

int get_front(int ind)
{
    if(q[ind].empty())
        return 0;
    return q[ind].front();
}

int get_min()
{
    int i1 = get_front(0), i2 = get_front(1);
    if(v[i1].val < v[i2].val)
    {
        q[0].pop();
        return i1;
    }
    else
    {
        q[1].pop();
        return i2;
    }
}

void dfs(int nod, int d, long long cod)
{
    if(nod <= n)
    {
        ans[nod] = cod;
        depth[nod] = d;
        return;
    }
    dfs(v[nod].st, d + 1, 2 * cod);
    dfs(v[nod].dr, d + 1, 2 * cod + 1);
}

int main()
{
    fin >> n;
    v[0].val = inf;
    for(int i = 1; i <= n; i++)
    {
        fin >> v[i].val;
        v[i].nod = i;
        q[0].push(i);
    }
    int ind = n;
    while(q[0].size() + q[1].size() > 1)
    {
        int a, b;
        a = get_min();
        b = get_min();
        ++ind;
        v[ind] = {v[a].val + v[b].val, ind, a, b};
        q[1].push(ind);
        len += v[ind].val;
    }
    dfs(ind, 0, 0);
    fout << len << '\n';
    for(int i = 1; i <= n; i++)
        fout << depth[i] << ' ' << ans[i] << '\n';
    return 0;
}