Cod sursa(job #2419370)

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

#define llg long long
#define llg_pair std::pair <llg, llg>

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

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

        std::priority_queue <llg_pair, std::vector <llg_pair>, std::greater <llg_pair>> pq;
        for (llg i=0; i<tree.size(); ++i)
            pq.push({tree[i].rang, i});
        llg_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(llg vertex, llg encoding = 0, llg lvl = 0) {
        if (tree[vertex].son[0] == -1 && tree[vertex].son[1] == -1) {
            lg[vertex] = lvl;
            b[vertex] = encoding;
            return;
        }

        for (llg 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, llg son0 = -1, llg son1 = -1) : rang(rang) {son[0] = son0; son[1] = son1;}
        llg rang, son[2];
    };
public:
    std::vector <node> tree;
};

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

llg N;
std::vector <llg> 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 (llg i=0; i<huffman.tree.size(); ++i)
        sum += huffman.tree[i].rang;
    for (auto &it:freq)
        sum -= it;
    output << sum << '\n';

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

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

    return 0;
}