Cod sursa(job #2246810)

Utilizator paul_danutDandelion paul_danut Data 27 septembrie 2018 16:22:00
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

ifstream f("huffman.in");
ofstream g("huffman.out");

struct Nod { int pos, val; Nod *next, *left, *right; };

bool cmp(Nod* x, Nod* y)
{
    return x->val > y->val;
}

int n, i;
long long unsigned a[1000001];
long long unsigned len[1000001];
long long unsigned code[1000001];

Nod* Huffman(std::vector<Nod*>& heap)
{
    while (heap.size()>1)
    {
        Nod *c1 = heap.front();
        std::pop_heap (heap.begin(), heap.end(), cmp); heap.pop_back();
        Nod *c2 = heap.front();
        std::pop_heap (heap.begin(), heap.end(), cmp); heap.pop_back();

        Nod* p = new Nod;
        p->val = c1->val + c2->val;

        p->left = c1;
        p->right = c2;

        heap.push_back(p); std::push_heap (heap.begin(), heap.end(), cmp);
    }

    return heap.front();
}

void DepthFirst(Nod* nod, long long int val = 0, int length = 0)
{
    if (nod->left != nullptr)
    {
        DepthFirst(nod->left, val * 2, length + 1);
    }

    if (nod->right != nullptr)
    {
        DepthFirst(nod->right, val * 2 + 1, length + 1);
    }


    if (nod->right == nullptr && nod->left == nullptr)
    {
        len[nod->pos] = length;
        code[nod->pos] = val;
    }
}



int main()
{
    std::vector<Nod*> heap;

    f >> n;
    for (i = 0; i<n; i++)
    {
        f >> a[i];
        Nod *nod = new Nod;
        nod->pos = i;
        nod->val = a[i];
        nod->left = nullptr;
        nod->right = nullptr;

        heap.push_back(nod); std::push_heap (heap.begin(), heap.end());
    }

    for (i = 0; i<n; i++)
    {

    }

    std::make_heap (heap.begin(), heap.end(), cmp);

    Nod* root;
    root = Huffman(heap);
    //DepthFirst(root);

    long long unsigned lg = 0;
    for (i = 0; i < n; i++)
    {
        lg += len[i] * a[i];
    }

    g << lg << '\n';

    for (i = 0; i < n; i++)
    {
        g << len[i] << ' ' << code[i] << '\n';
    }

    f.close();
    g.close();

    return 0;
}