Cod sursa(job #1996874)

Utilizator FlameingoAiordachioaei Marius Flameingo Data 2 iulie 2017 21:10:28
Problema Coduri Huffman Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include<cstdio>
#include<queue>

const int NMAX = 1000002;
using namespace std;

class node
{
public:
    node(const int value) : left(nullptr), right(nullptr)
    {
        this->value = value;
    }
    node *left, *right;
    int value;
};

class leaf_node: public node
{
public:
    leaf_node(const int val, const int sym) : node(val)
    {
        this->symbol = sym;
    }
    int symbol;
};

struct predicate
{
    bool operator () (const node *left, const node *right)
    {
        return left->value > right->value;
    }
};

int N;
priority_queue<node*, vector<node*>, predicate> pq;

int len[NMAX], code[NMAX];

void dfs(node* current, int &sum, int path = 0, int depth = 0)
{
    if (current->left == nullptr && current->right == nullptr)
    {
        int sym = ((leaf_node*)current)->symbol;
        len[sym] = depth;
        code[sym] = path;
        return;
    }
    sum += current->value;
    if (current->left != nullptr)
        dfs(current->left, sum, path * 2, depth + 1);
    if (current->right != nullptr)
        dfs(current->right, sum, path * 2 + 1, depth + 1);
}

int main()
{
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);

    scanf("%d", &N);
    for (int i = 0; i < N; ++i)
    {
        int val;
        scanf("%d", &val);
        pq.push(new leaf_node(val, i));
    }

    while(pq.size() != 1)
    {
        node* current_l = pq.top();
        pq.pop();
        node* current_r = pq.top();
        pq.pop();

        node *parent = new node(current_l->value + current_r->value);
        parent->left = current_l;
        parent->right = current_r;

        pq.push(parent);
    }
    int tot_sum = 0;
    dfs(pq.top(), tot_sum);
    printf("%d\n", tot_sum);
    for (int i = 0; i < N; ++i) {
        printf("%d %d\n", len[i], code[i]);
    }

}