Cod sursa(job #3135869)

Utilizator vladp1324Vlad Pasare vladp1324 Data 4 iunie 2023 16:36:51
Problema Coduri Huffman Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <queue>
#define NMAX 10000001
#define INF 1LL * 1000000000 * 1000000000

using namespace std;

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

struct Nod{
    long long fr;
    int fiu[2];
} nod[2*NMAX];

priority_queue<pair<long long, int>> pq;
int n, lg[2*NMAX];
long long total, b[2*NMAX];

void dfs(int poz, long long cod, int nivel){
    if(nod[poz].fiu[0]){
        dfs(nod[poz].fiu[0], cod*2, nivel+1);
        dfs(nod[poz].fiu[1], cod*2+1, nivel+1);
        return;
    }
    lg[poz] = nivel;
    b[poz] = cod;
}

void solve(){

    int nc = n;
    for(int l = 1; l <= n - 1; l++){
        nc++;
        for(int i = 0; i < 2; i++){
            int pozMin = pq.top().second;
            long long mn = -pq.top().first;
            pq.pop();
            nod[nc].fiu[i] = pozMin;
            nod[nc].fr += nod[pozMin].fr;
        }
        pq.push({-nod[nc].fr, nc});
        total += nod[nc].fr;
    }
    dfs(nc, 0, 0);
}

int main()
{
    fin >> n;
    for(int i = 1; i <= n; i++){
        fin >> nod[i].fr;
        pq.push({-nod[i].fr, i});
    }
    solve();
    fout << total << '\n';
    for(int i = 1; i <= n; i++)
        fout << lg[i] << ' ' << b[i] << '\n';
    return 0;
}