Cod sursa(job #3267933)

Utilizator BOSSSTEFANPetrescu Ioan Stefan BOSSSTEFAN Data 12 ianuarie 2025 22:40:33
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
#define inf 1e18 + 1
using namespace std;
const int nmax = 1e6;
queue <int> q1, q2;
long long v[nmax * 2 + 1];
int l[nmax * 2 + 1], r[nmax * 2 + 1];
struct ura
{
    long long val, nrb;
}sol[nmax + 1];
long long rez;
int n;
void dfs(int nod, int p, long long val)
{
    if(nod <= n)
    {
        sol[nod].nrb = p;
        sol[nod].val = val;
        rez += v[nod] * p;
        return;
    }
    dfs(l[nod], p + 1, val * 2);
    dfs(r[nod], p + 1, val * 2 + 1);
}
int getmin()
{
    int x = 0, y = 0;
    if(!q1.empty())
        x = q1.front();
    if(!q2.empty())
        y = q2.front();
    if(x == 0 || v[y] <= v[x])
    {
        q2.pop();
        return y;
    }
    q1.pop();
    return x;
}
int main()
{
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);
    ios :: sync_with_stdio(false);
    cin.tie(0);
    int i, x, y;
    long long nr;
    cin >> n;
    v[0] = inf;
    for(i = 1; i <= n; i++)
    {
        cin >> nr;
        q1.push(i);
        v[i] = nr;
    }
    while(q1.size() + q2.size() > 1)
    {
        x = getmin();
        y = getmin();
        q2.push(i);
        v[i] = v[x] + v[y];
        l[i] = x;
        r[i] = y;
        i++;
    }
    dfs(n * 2 - 1, 0, 0);
    cout << rez << '\n';
    for(i = 1; i <= n; i++)
        cout << sol[i].nrb << " " << sol[i].val << '\n';
    return 0;
}