Cod sursa(job #902583)

Utilizator sebii_cSebastian Claici sebii_c Data 1 martie 2013 15:14:21
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <cstdio>

#include <queue>
#include <set>
#include <vector>

using namespace std;

struct node {
    node *left;
    node *right;
    long long val;

    node(long long _val, node *_left, node *_right): 
        val(_val), left(_left), right(_right) {}
};

struct node_comp {
    bool operator()(const node *a, const node *b) {
        return a->val > b->val;
    }
};

void dfs(node *root, int d, int val)
{
    if (root->left == NULL && root->right == NULL) {
        printf("%d %d\n", d, val);
        return;
    }

    dfs(root->left, d + 1, val << 1);
    dfs(root->right, d + 1, (val << 1) + 1);
}

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

    int n;
    scanf("%d", &n);

    priority_queue<node *, vector<node *>, node_comp> tree;
    for (int i = 0; i < n; ++i) {
        long long v;
        scanf("%lld", &v);
        tree.push(new node(v, NULL, NULL));
    }

    node *root;
    long long total_value = 0;
    while (true) {
        node *low = tree.top();
        tree.pop();
        if (tree.empty()) {
            root = low;
            break;
        }

        node *next = tree.top();
        tree.pop();
        tree.push(new node(low->val + next->val, low, next));

        total_value += low->val;
        total_value += next->val;
    }

    printf("%lld\n", total_value);
    dfs(root, 0, 0);

    return 0;
}