Cod sursa(job #1166855)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 3 aprilie 2014 21:19:24
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

typedef long long int64;

const int NIL = -1;
const int BASE = 2;

vector< vector<int> > Tree;
vector<int> Levels, Codes;
int V;
vector<int64> Frequences;
int64 TotalLength;

int AddNode() {
    Tree.push_back(vector<int>());
    Levels.push_back(-1);
    return V++;
}

void AddEdge(const int from, const int to) {
    Tree[from].push_back(to);
}

void DFS(const int x, const int currentCode) {
    Codes[x] = currentCode;
    for (int i = 0; i < int(Tree[x].size()); ++i) {
        Levels[Tree[x][i]] = Levels[x] + 1;
        DFS(Tree[x][i], BASE * currentCode + i);
    }
}

template<class Type>
inline Type ExtractFront(queue<Type> &first, queue<Type> &second) {
    Type front;
    if (first.empty()) {
        front = second.front();
        second.pop();
    } else if (second.empty()) {
        front = first.front();
        first.pop();
    } else {
        if (first.front() < second.front()) {
            front = first.front();
            first.pop();
        } else {
            front = second.front();
            second.pop();
        }
    }
    return front;
}

void GetHuffmanCodes() {
    queue< pair<int64, int> > terminal, internal;
    for (int i = 0; i < int(Frequences.size()); ++i)
        terminal.push(make_pair(Frequences[i], AddNode()));
    while (int(terminal.size()) + int(internal.size()) > 1) {
        pair<int64, int> x = ExtractFront< pair<int64, int> >(terminal, internal);
        pair<int64, int> y = ExtractFront< pair<int64, int> >(terminal, internal);
        int z = AddNode();
        AddEdge(z, x.second);
        AddEdge(z, y.second);
        internal.push(make_pair(x.first + y.first, z));
    }
    Codes = vector<int>(V);
    Levels[V - 1] = 0;
    DFS(V - 1, 0);
    Codes.resize(int(Frequences.size()));
}

void Solve() {
    GetHuffmanCodes();
    TotalLength = 0;
    for (int i = 0; i < int(Frequences.size()); ++i)
        TotalLength += Frequences[i] * Levels[i];
}

void Read() {
    ifstream cin("huffman.in");
    int n;
    cin >> n;
    Frequences = vector<int64>(n);
    for (int i = 0; i < n; ++i)
        cin >> Frequences[i];
    cin.close();
}

void Print() {
    ofstream cout("huffman.out");
    cout << TotalLength << "\n";
    for (int i = 0; i < int(Frequences.size()); ++i)
        cout << Levels[i] << " " << Codes[i] << "\n";
    cout.close();
}

int main() {
    Read();
    Solve();
    Print();
    return 0;
}