Cod sursa(job #2419375)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 8 mai 2019 11:48:57
Problema Coduri Huffman Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <bits/stdc++.h>

#define llg long long
#define int_pair std::pair <int, int>

class HuffmanCoding {
public:
    std::vector <int> lg;
    std::vector <llg> bits;
    HuffmanCoding(const std::vector <int>& frequencies) {
        buildTree(frequencies);
        lg.resize(tree.size());
        bits.resize(tree.size());
        DFS(tree.size()-1);
    }

private:
    void buildTree(const std::vector <int>& frequencies) {
        tree.resize(frequencies.size());
        for (int i=0; i<tree.size(); ++i)
            tree[i].rang = frequencies[i];

        std::priority_queue <int_pair, std::vector <int_pair>, std::greater <int_pair>> pq;
        for (int i=0; i<tree.size(); ++i)
            pq.push({tree[i].rang, i});
        int_pair p1, p2;

        while (pq.size() >= 2) {
            p1 = pq.top(); pq.pop();
            p2 = pq.top(); pq.pop();
            tree.push_back(node(tree[p1.second].rang + tree[p2.second].rang, p1.second, p2.second));
            pq.push({tree.back().rang, tree.size()-1});
        }
    }

    void DFS(int vertex, llg encoding = 0, int lvl = 0) {
        if (tree[vertex].son[0] == -1 && tree[vertex].son[1] == -1) {
            lg[vertex] = lvl;
            bits[vertex] = encoding;
            return;
        }

        for (int i=0; i<2; ++i)
            if (tree[vertex].son[i] != -1)
                DFS(tree[vertex].son[i], 2*encoding + i, lvl+1);
    }
protected:
    struct node {
        node(llg rang = 0, int son0 = -1, int son1 = -1) : rang(rang) {son[0] = son0; son[1] = son1;}
        llg rang; int son[2];
    };
public:
    std::vector <node> tree;
};

const int MAXN = 1e6 + 5;
const llg INF  = 1e18;

int N;
std::vector <int> freq;

std::ifstream input ("huffman.in");
std::ofstream output("huffman.out");

void readInput() {
    input >> N;
    freq.resize(N);
    for (auto &it:freq)
        input >> it;
}

void solveInput() {
    HuffmanCoding huffman(freq);

    llg sum = 0;
    for (int i=0; i<huffman.tree.size(); ++i)
        sum += huffman.tree[i].rang;
    for (auto &it:freq)
        sum -= it;
    output << sum << '\n';

    for (int i=0; i<N; ++i)
        output << huffman.lg[i] << ' ' << huffman.bits[i] << '\n';
}

int main()
{
    readInput();
    solveInput();

    return 0;
}