Cod sursa(job #1988028)

Utilizator Alexandra_MMihaila Alexandra Alexandra_M Data 1 iunie 2017 21:37:46
Problema Coduri Huffman Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <fstream>
#include <algorithm>
#include <cstring>

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

struct element
{
    int lg, nr_b10;
}sol[1000001];

struct nod
{
    int element, frecv;
    nod * stang, * drept;
}*aux[1000001];

int n;

bool compare(nod * a, nod * b)
{
    return a->frecv > b->frecv;
}

void conversie(char * cod, int i)
{
    int rez = 0, p2 = 1;
    for (int i = strlen(cod) - 1; i >= 0; --i)
    {
        if (cod[i] == '1')
            rez += p2;
        p2 *= 2;
    }
    sol[i].nr_b10 = rez;
    sol[i].lg = strlen(cod);
}

void RSD(nod * arb, int &s, char * cod, char * fiu)
{
    if (!arb)
        return;
    if (arb->stang && arb->drept)
        s += arb->stang->frecv + arb->drept->frecv;
    char cod_nou[strlen(cod) + 1];
    strcpy(cod_nou,cod);
    strcat(cod_nou,fiu);
    if (arb->element != -1)
        conversie(cod_nou,arb->element);
    RSD(arb->stang,s,cod_nou,"0");
    RSD(arb->drept,s,cod_nou,"1");
}

int main()
{
    fin>>n;
    fin.get();
    for (int i = 0; i < n; ++i)
    {
        int x;
        fin >> x;
        nod * p = new nod;
        p->element = i;
        p->frecv = x;
        p->stang = NULL;
        p->drept = NULL;
        aux[i] = p;
    }
    sort(aux, aux + n, compare);
    int cn = n;
    while (cn > 1)
    {
         nod * p = new nod;
         p->element = -1;
         p->frecv = aux[cn-1]->frecv + aux[cn-2]->frecv;
         p->stang = aux[cn-1];
         p->drept = aux[cn-2];
        --cn;
        aux[cn-1] = p;
        sort(aux, aux + cn, compare);
    }
    int s = aux[0]->frecv;
    int s1 = 0, s2 = 0;
    RSD(aux[0]->stang, s1, "","0");
    s += s1;
    RSD(aux[0]->drept, s2,"","1");
    s += s2;
    fout << s << '\n';
    for (int i = 0; i < n; ++i)
        fout << sol[i].lg << ' ' << sol[i].nr_b10 << '\n';
    return 0;
}