Cod sursa(job #2888883)

Utilizator bogdanputineluBogdan Putinelu bogdanputinelu Data 11 aprilie 2022 22:04:32
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <climits>
using namespace std;
struct nod{
    long long val;
    int st, dr, niv;
}noduri[2 * 1000010];
int n;
long long total;
void dfs(int nod, int niv, long long val){
    if(nod > 0)
    {
        noduri[nod].val = val;
        noduri[nod].niv = niv;
        dfs(noduri[nod].st, niv + 1, val * 2);
        dfs(noduri[nod].dr, niv + 1, (val + 1) * 2);
    }
}
void huffman(){
    noduri[n + 1].val = LONG_LONG_MAX;
    int i, j, stop, prim, sec;
    i = 1;
    j = n+2;
    stop = n+1;
    while(i <= n || j < stop){
        if(j <= stop && noduri[j].val < noduri[i].val) {
            prim = j;
            ++j;
        }
        else {
            prim = i;
            ++i;
        }
        if(j <= stop && noduri[j].val < noduri[i].val) {
            sec = j;
            ++j;
        }
        else {
            sec = i;
            ++i;
        }
        noduri[++stop].val = noduri[prim].val + noduri[sec].val;
        noduri[stop].st = prim;
        noduri[stop].dr = sec;
        total += noduri[stop].val;
    }
    dfs(stop, 0, 0);
}
int main() {
    ifstream f("huffman.in");
    ofstream g("huffman.out");
    f >> n;
    for(int i = 1; i <= n; ++i)
        f >> noduri[i].val;
    huffman();
    g << total << '\n';
    for(int i = 1; i <= n; ++i)
        g << noduri[i].niv << ' ' << noduri[i].val << '\n';
    return 0;
}