Cod sursa(job #2897603)

Utilizator ProBatmanBalint Leonard ProBatman Data 4 mai 2022 10:08:59
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;

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

const int CMAX = 2e6+15;;

int n;
long long temp;
struct noduri{
    int st, dr , niv;
    long long val;
}heap[CMAX];

void read(){
    fin >> n;
    //cout << n << '\n';
    for(int i=1;i<=n;i++)
    {
        fin >> heap[i].val;
        //cout << heap[i].val << '\n';
    }
}

void parc_srd(int nod,int niv, long long val){
    if(nod>0){
    //cout << heap[nod].val << " " << nod << " " << val << '\n';
    heap[nod].val = val;
    heap[nod].niv = niv;
    parc_srd(heap[nod].st,niv+1,val*2);
    parc_srd(heap[nod].dr,niv+1,(val*2)+1);
    }
}

void huffman(){
    heap[n+1].val = LONG_LONG_MAX;
    int i, j, stop , st , dr;
    i = 1;
    j = n+2;
    stop = n+1;
    while(i < n+1 || j < stop){
        if(j <= stop && heap[j].val <= heap[i].val)
                st = j++;
        else{
            st = i++;
        }
        if(j <= stop && heap[j].val <= heap[i].val){
            dr = j++;
        }
        else
        {
            dr = i++;
        }
        heap[++stop].val = heap[st].val + heap[dr].val;
        heap[stop].st = st;
        heap[stop].dr = dr;
        //heap[stop].niv = max(heap[heap[stop].st].val,heap[heap[stop].dr].val) + 1;
        temp = temp + heap[stop].val;
    }
    parc_srd(stop,0,0);
}

int main()
{
    read();
    huffman();
    fout << temp << '\n';
    for(int i=1;i<=n;i++)
    {
        fout << heap[i].niv << " " << heap[i].val << '\n';
    }
    return 0;
}