Cod sursa(job #3234200)

Utilizator Sabin1133Padurariu Sabin Sabin1133 Data 6 iunie 2024 23:26:03
Problema Coduri Huffman Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <fstream>

#include <queue>

std::ifstream fin;
std::ofstream fout;

class Node {
private:
    int _symbol;
    long _freq;
    Node *_left, *_right;

public:
    Node(long freq, Node *left = nullptr, Node *right = nullptr) : _symbol(0), _freq(freq), _left(left), _right(right) {}
    Node(int symbol, long freq) : _symbol(symbol), _freq(freq), _left(nullptr), _right(nullptr) {}
    
    int symbol()
    {
        return this->_symbol;
    }

    long freq()
    {
        return this->_freq;
    }

    Node *left()
    {
        return this->_left;
    }

    Node *right()
    {
        return this->_right;
    }

    bool operator<(Node &other)
    {
        return this->_freq < other.freq();
    }
};

class Node_Comp {
public:
    bool operator()(Node *node1, Node *node2)
    {
        return node1->freq() > node2->freq();
    }
};

long long find_encoding(Node *root, int depth, int base10_encoding, std::vector<std::pair<int, int>> &encoding)
{
    long long sum = 0;

    if (root->symbol()) {
        encoding.push_back({depth, base10_encoding});
        return sum;
    }

    sum += find_encoding(root->left(), depth + 1, base10_encoding, encoding);
    sum += find_encoding(root->right(), depth + 1, base10_encoding + (1 << depth), encoding);

    return sum + root->freq();
}

int main()
{
    int n;
    std::priority_queue<Node *, std::vector<Node *>, Node_Comp> pq;
    Node *root = nullptr;
    std::vector<std::pair<int, int>> encoding;


    fin.open("huffman.in");
    fout.open("huffman.out");

    fin >> n;

    for (int f, i = 1; i <= n; ++i) {
        fin >> f;
        pq.push(new Node(i, f));
    }


    while (pq.size() > 1) {
        auto node1 = pq.top();
        pq.pop();
        auto node2 = pq.top();
        pq.pop();

        pq.push(new Node(node1->freq() + node2->freq(), node1, node2));
    }

    root = pq.top();
    pq.pop();


    fout << find_encoding(root, 0, 0, encoding) << '\n';

    for (auto enc : encoding)
        fout << enc.first << ' ' << enc.second << '\n';

    fin.close();
    fout.close();

    return 0;
}