Cod sursa(job #3267928)

Utilizator BOSSSTEFANPetrescu Ioan Stefan BOSSSTEFAN Data 12 ianuarie 2025 22:20:03
Problema Coduri Huffman Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define inf 1e18 + 1
using namespace std;
const int nmax = 1e6;
queue <pair<long long, int>> q1, q2;
vector <int> g[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;
        rez += sol[nod].val * p;
        sol[nod].val = val;
        return;
    }
    dfs(g[nod][0], p + 1, val * 2);
    dfs(g[nod][1], p + 1, val * 2 + 1);
}
pair <long long, int> getmin()
{
    pair <long long, int> x;
    if(q1.empty())
    {
        x = q2.front();
        q2.pop();
        return x;
    }
    if(q2.empty())
    {
        x = q1.front();
        q1.pop();
        return x;
    }
    if(q1.front().first <= q2.front().first)
    {
        x = q1.front();
        q1.pop();
        return x;
    }
    x = q2.front();
    q2.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;
    pair <long long, int> x, y;
    cin >> n;
    for(i = 1; i <= n; i++)
    {
        cin >> sol[i].val;
        q1.push({sol[i].val, i});
    }
    while(q1.size() + q2.size() > 1)
    {
        x = getmin();
        y = getmin();
        q2.push({x.first + y.first, i});
        g[i].push_back(x.second);
        g[i].push_back(y.second);
        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;
}