Cod sursa(job #1335802)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 5 februarie 2015 21:42:01
Problema Coduri Huffman Scor 75
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <fstream>

#define Nmax 1000100

using namespace std;

class Node {

    public:
        int son[2];
        long long frequency;

} node[Nmax << 1];

class Queue {

    private:
        int left, right, V[Nmax];

    public:
        Queue() {
            left = right = 0;
        }

        void push(int value) {
            V[right++] = value;
        }

        int pop() {
            ++left;
            return V[left - 1];
        }

        int front() {
            return V[left];
        }

        int size() {
            return (right - left);
        }

        bool empty() {
            return (size() == 0);
        }

} A, B;

int N, Length[Nmax];
long long totalLength, Answer[Nmax];

void Dfs(int nodeId, long long binaryCode, int level) {

    if(node[nodeId].son[0] != 0) {
        Dfs(node[nodeId].son[0], (binaryCode << 1), level + 1);
        Dfs(node[nodeId].son[1], (binaryCode << 1) | 1, level + 1);
        return;
    }

    Answer[nodeId] = binaryCode;
    Length[nodeId] = level;
}
int findMin() {

    if(A.empty())
        return B.pop();

    if(B.empty())
        return A.pop();

    if(node[A.front()].frequency < node[B.front()].frequency)
        return A.pop();
    else
        return B.pop();

}
void Solve() {

    int i, x, y, top;

    top = N;

    for(i = 1; i < N; i++) {

        x = findMin();
        y = findMin();

        node[++top].frequency = node[x].frequency + node[y].frequency;
        node[top].son[0] = x;
        node[top].son[1] = y;

        B.push(top);
        totalLength += node[top].frequency;
    }

    Dfs(top, 0, 0);

}
void Read() {

    ifstream in("huffman.in");
    in >> N;

    for(int i = 1; i <= N; i++) {
        in >> node[i].frequency;
        A.push(i);
    }

    in.close();
}
void Write() {

    ofstream out("huffman.out");
    out << totalLength << '\n';

    for(int i = 1; i <= N; i++)
        out << Length[i] << ' ' << Answer[i] << '\n';

    out.close();
}
int main() {

    Read();
    Solve();
    Write();

    return 0;
}