Cod sursa(job #2274029)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 1 noiembrie 2018 11:13:01
Problema Coduri Huffman Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

struct nod
{
    nod(long long val = -1)
    {
        this->val = val;
        ind = -1;
        child[0] = child[1] = NULL;
    }
    void AddChildren(nod * x, nod * y)
    {
        child[0] = x, child[1] = y;
    }
    nod * child[2];
    long long val;
    int ind;
};

nod* GetMin(queue<nod*> &a, queue<nod*> &b)
{
    nod * ret;
    if(a.empty() == false && (b.empty() == true || a.front()->val < b.front()->val))
    {
        ret = a.front();
        a.pop();
    }
    else
    {
        ret = b.front();
        b.pop();
    }
    return ret;
}

int lg;
long long cod;
long long total;
vector<pair<int, long long> > rasp;

void DFS(const nod * current)
{
    if(current->child[0] != NULL)
    {
        for(int i = 0; i < 2; ++i)
        {
            lg++;
            cod = (cod << 1) + i;
            DFS(current->child[i]);
            lg--;
            cod >>= 1;
        }
    }
    if(current->ind != -1)
        rasp[current->ind] = make_pair(lg, cod);
    else
        total += current->val;
}

int main()
{
    ifstream in("huffman.in");
    int n;
    in >> n;
    rasp.resize(n);
    queue<nod*> qElem, qSum;
    long long x;
    nod * t;
    for(int i = 0; i < n; ++i)
    {
        in >> x;
        t = new nod(x);
        t->ind = i;
        qElem.push(t);
    }
    in.close();

    nod *a, *b;
    while(qElem.size() + qSum.size() > 1)
    {
        a = GetMin(qElem, qSum), b = GetMin(qElem, qSum);
        t = new nod(a->val + b->val);
        t->AddChildren(a, b);
        qSum.push(t);
    }
    t = GetMin(qElem, qSum);
    DFS(t);

    ofstream out("huffman.out");
    out << total << "\n";
    for(int i = 0; i < n; ++i)
        out << rasp[i].first << " " << rasp[i].second << "\n";
    out.close();
    return 0;
}