Cod sursa(job #2758112)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 8 iunie 2021 17:41:23
Problema Coduri Huffman Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <bits/stdc++.h>
using namespace std;
long long s;
struct data
{
    long long nr, len;
}auxi;
struct Nod
{
    long long nr_ord;  //numarul de ordine (primul/al doilea/ al n-lea elem)
    long long fr;      // frecv
    Nod* left;
    Nod* right;
};
data rez[1000005];
struct cmp
{
    bool operator()(Nod* a, Nod* b)
    {
        return a -> fr > b -> fr;
    }
};
long long get_nr(string alfa)
{
    long long ans = 0;
    for(auto it : alfa)
    {
        if(it == '0') ans = ans * 2;
        if(it == '1') ans = ans * 2 + 1;
    }
    return ans;
}
void span(Nod *& node, string & a)
{
    if(node -> nr_ord != 0)
    {
        s = s + a.size() * node -> fr;
        auxi.len = a.size();
        auxi.nr = get_nr(a);
        rez[node -> nr_ord] = auxi;
    }
    if(node -> right != NULL)
    {
        a = a + "1";
        span(node -> right, a);
        a.pop_back();
    }
    if(node -> left != NULL)
    {
        a = a + "0";
        span(node -> left, a);
        a.pop_back();
    }
}
priority_queue <Nod*, vector <Nod*>, cmp> Q;
long long i, n, x;
Nod *root, *aux, *aux1, *aux2;
string a;
int main()
{
    ifstream f("huffman.in");
    ofstream g("huffman.out");
    f >> n;
    for(i = 1; i <= n; i ++)
    {
        f >> x;
        aux = new Nod;
        aux -> left = NULL;
        aux -> right = NULL;
        aux -> fr = x;
        aux -> nr_ord = i;
        Q.push(aux);
    }
    while(!Q.empty())
    {
        aux = Q.top();
        Q.pop();
        if(Q.empty())break;
        aux1 = Q.top();
        Q.pop();
        root = new Nod;
        root -> nr_ord = 0;
        root -> fr = aux -> fr + aux1 -> fr;
        root -> left = aux;
        root -> right = aux1;
        Q.push(root);
    }
    root = aux;
    span(root, a);
    g << s << "\n";
    for(i = 1; i <= n; i ++)
        g << rez[i].len << " " << rez[i].nr << "\n";
    return 0;
}