Cod sursa(job #2274018)

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

using namespace std;

struct nod
{
    nod(long long val = -1)
    {
        this->val = val;
        ind = -1;
    }
    void AddChild(nod * x)
    {
        child.push_back(x);
    }
    vector<nod*> child;
    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;
}

void DFS(const nod * current, vector<pair<int, long long> > &rasp, int lg, long long x, long long &total)
{
    for(int i = 0; i < current->child.size(); ++i)
        DFS(current->child[i], rasp, lg+1, (x << 1) + i, total);
    if(current->ind != -1)
        rasp[current->ind] = make_pair(lg, x);
    else
        total += current->val;
}

int main()
{
    ifstream in("huffman.in");
    int n;
    in >> n;
    vector<pair<int, long long> > rasp(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->AddChild(a);
        t->AddChild(b);
        qSum.push(t);
    }
    t = GetMin(qElem, qSum);
    long long total = 0;
    DFS(t, rasp, 0, 0, total);

    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;
}