Cod sursa(job #1307885)

Utilizator gabrieligabrieli gabrieli Data 2 ianuarie 2015 23:41:29
Problema Coduri Huffman Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdint>
#include <algorithm>
#include <fstream>
#include <queue>
#include <vector>
#include <memory>
#include <map>
using namespace std;
 
struct Node;
 
typedef shared_ptr<Node> node_t;
 
struct Node {
    uint64_t w;
    node_t left;
    node_t right;
     
    Node(uint64_t w, node_t left = nullptr, node_t right = nullptr)
    : w {w}, left {left}, right {right}
    {}
};
 
struct cmp_greater {
    bool operator()(const node_t& a, const node_t& b) {
        return a->w > b->w;
    }
};
 
uint64_t df(node_t node, map<int, vector<uint64_t>>& alph, uint64_t rep = 0, int h = 0) {
    while (node->left && node->right)
        return node->w +
                df(node->left, alph, rep << 1, h + 1) +
                df(node->right, alph, (rep << 1) + 1, h + 1);
     
    alph[h].push_back(rep);
    return 0;
}
 
int main() {
    ifstream fin("huffman.in");
    ofstream fout("huffman.out");
     
    int n; fin >> n;
     
    // min priority queue
    priority_queue<node_t, vector<node_t>, cmp_greater> Q;
    for (uint64_t x; n--;) {
        fin >> x;
        Q.push(make_shared<Node>(x));
    }
     
    // build Huffman tree
    while (Q.size() > 1) {
        node_t l = Q.top(); Q.pop();
        node_t r = Q.top(); Q.pop();
        Q.push(make_shared<Node>(l->w + r->w, l, r));
    }
     
    map<int, vector<uint64_t>> alph;  
    fout << df(Q.top(), alph) << '\n';  
        
    for (auto it = alph.rbegin(); it != alph.rend(); ++it)
        for (auto rep : it->second)
            fout << (it->first) << ' ' << rep << '\n';
             
    return 0;
}