Prima di u principiu di u corsu
A codificazione Huffman hè un algoritmu di cumpressione di dati chì formula l'idea basica di cumpressione di fugliale. In questu articulu, parlemu di codificazione di lunghezza fissa è variabile, codici unicu decodificabili, reguli di prefissu, è custruisce un arbre Huffman.
Sapemu chì ogni caratteru hè almacenatu cum'è una sequenza di 0 è 1 è occupa 8 bits. Questu hè chjamatu codificazione di lunghezza fissa perchè ogni caratteru usa u listessu numeru fissu di bits per almacenà.
Dicemu chì avemu datu un testu. Cumu pudemu riduce a quantità di spaziu necessariu per almacenà un caratteru unicu?
L'idea principale hè a codificazione di lunghezza variabile. Pudemu aduprà u fattu chì certi caratteri in u testu sò più spessu chì altri (
Cumu, sapendu a sequenza di bit, decodificà senza ambiguità?
Cunsiderate a linea "abacdab". Hà 8 caratteri, è quandu si codifica una lunghezza fissa, avarà bisognu di 64 bits per almacenà. Nota chì a frequenza di u simbulu "a", "b", "c" и "D" uguali 4, 2, 1, 1 rispettivamente. Pruvemu d'imagine "abacdab" menu bits, usendu u fattu chì "à" accade più freti chè "B"e "B" accade più freti chè "c" и "D". Cuminciamu per codificà "à" cun un bit uguale à 0, "B" assigneremu un codice di dui bit 11, è usendu trè bit 100 è 011 codificaremu "c" и "D".
In u risultatu, averemu:
a
0
b
11
c
100
d
011
Allora a linea "abacdab" avemu da codificà cum'è 00110100011011 (0|0|11|0|100|011|0|11)usendu i codici sopra. Tuttavia, u prublema principali serà in a decodificazione. Quandu avemu pruvatu à decodificà a stringa 00110100011011, avemu un risultatu ambiguu, postu chì pò esse rapprisintatu cum'è:
0|011|0|100|011|0|11 adacdab
0|0|11|0|100|0|11|011 aabacabd
0|011|0|100|0|11|0|11 adacabab
...
è cusì.
Per evitari sta ambiguità, duvemu assicurà chì a nostra codificazione satisface un tali cuncettu cum'è regula di prefissu, chì à u turnu implica chì i codici ponu esse decodificati solu in un modu unicu. A regula di prefissu assicura chì nisun codice hè un prefissu di un altru. Per codice, intendemu i bits utilizati per rapprisintà un caratteru particulari. In l'esempiu sopra 0 hè un prefissu 011, chì viola a regula di prefissu. Allora, se i nostri codici satisfacenu a regula di prefissu, pudemu decodificà unicu (è vice versa).
Rivedemu l'esempiu sopra. Sta volta avemu da assignà simboli "a", "b", "c" и "D" codici chì soddisfanu a regula di prefissu.
a
0
b
10
c
110
d
111
Cù sta codificazione, a stringa "abacdab" serà codificata cum'è 00100100011010 (0|0|10|0|100|011|0|10). Eccu quì 00100100011010 seremu digià capaci di decodificà senza ambiguità è vultà à a nostra stringa originale "abacdab".
Codificazione di Huffman
Avà chì avemu trattatu di a codificazione di lunghezza variabile è a regula di prefissu, parlemu di a codificazione Huffman.
U metudu hè basatu annantu à a creazione di l'arburi binari. In questu, u node pò esse sia finali sia internu. In principiu, tutti i nodi sò cunsiderati foglie (terminali), chì rapprisentanu u simbulu stessu è u so pesu (vale à dì, a freccia di l'occurrence). I nodi internu cuntenenu u pesu di u caratteru è riferite à dui nodi discendenti. Per accordu generale, pocu "0" rapprisenta seguitu u ramu manca, è "1" - à diritta. in piena arbre N foglie è N-1 nodi interni. Hè ricumandemu chì quandu si custruisce un arbre Huffman, i simboli inutilizati sò scartati per ottene codici di lunghezza ottimali.
Aduprà una fila di priorità per custruisce un arbre Huffman, induve u node cù a freccia più bassa serà datu a priorità più alta. I passi di custruzzione sò descritti quì sottu:
- Crea un node foglia per ogni caratteru è aghjunghje à a fila di priorità.
- Mentre ci hè più di una foglia in a fila, fate u seguente:
- Eliminate i dui nodi cù a più alta priorità (frequenza più bassa) da a fila;
- Crea un novu nodu internu, induve sti dui nodi seranu figlioli, è a freccia di l'occurrence serà uguali à a summa di e frequenze di sti dui nodi.
- Aghjunghjite un novu node à a fila di priorità.
- L'unicu node restante serà a radica, è questu compie a custruzzione di l'arbulu.
Imagine chì avemu qualchì testu chì hè custituitu solu di caratteri "a", "b", "c", "d" и "è", è e so frequenze d'occurrence sò 15, 7, 6, 6 è 5, rispettivamente. Quì sottu sò illustrazioni chì riflettenu i passi di l'algoritmu.
Un percorsu da a radica à qualsiasi node finale guardà u codice prefissu ottimale (cunnisciutu ancu u codice Huffman) chì currisponde à u caratteru assuciatu à quellu nodu finale.
Arburu di Huffman
Quì sottu truverete l'implementazione di l'algoritmu di compressione Huffman in C++ è Java:
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
// A Tree node
struct Node
{
char ch;
int freq;
Node *left, *right;
};
// Function to allocate a new tree node
Node* getNode(char ch, int freq, Node* left, Node* right)
{
Node* node = new Node();
node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;
return node;
}
// Comparison object to be used to order the heap
struct comp
{
bool operator()(Node* l, Node* r)
{
// highest priority item has lowest frequency
return l->freq > r->freq;
}
};
// traverse the Huffman Tree and store Huffman Codes
// in a map.
void encode(Node* root, string str,
unordered_map<char, string> &huffmanCode)
{
if (root == nullptr)
return;
// found a leaf node
if (!root->left && !root->right) {
huffmanCode[root->ch] = str;
}
encode(root->left, str + "0", huffmanCode);
encode(root->right, str + "1", huffmanCode);
}
// traverse the Huffman Tree and decode the encoded string
void decode(Node* root, int &index, string str)
{
if (root == nullptr) {
return;
}
// found a leaf node
if (!root->left && !root->right)
{
cout << root->ch;
return;
}
index++;
if (str[index] =='0')
decode(root->left, index, str);
else
decode(root->right, index, str);
}
// Builds Huffman Tree and decode given input text
void buildHuffmanTree(string text)
{
// count frequency of appearance of each character
// and store it in a map
unordered_map<char, int> freq;
for (char ch: text) {
freq[ch]++;
}
// Create a priority queue to store live nodes of
// Huffman tree;
priority_queue<Node*, vector<Node*>, comp> pq;
// Create a leaf node for each character and add it
// to the priority queue.
for (auto pair: freq) {
pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
}
// do till there is more than one node in the queue
while (pq.size() != 1)
{
// Remove the two nodes of highest priority
// (lowest frequency) from the queue
Node *left = pq.top(); pq.pop();
Node *right = pq.top(); pq.pop();
// Create a new internal node with these two nodes
// as children and with frequency equal to the sum
// of the two nodes' frequencies. Add the new node
// to the priority queue.
int sum = left->freq + right->freq;
pq.push(getNode('', sum, left, right));
}
// root stores pointer to root of Huffman Tree
Node* root = pq.top();
// traverse the Huffman Tree and store Huffman Codes
// in a map. Also prints them
unordered_map<char, string> huffmanCode;
encode(root, "", huffmanCode);
cout << "Huffman Codes are :n" << 'n';
for (auto pair: huffmanCode) {
cout << pair.first << " " << pair.second << 'n';
}
cout << "nOriginal string was :n" << text << 'n';
// print encoded string
string str = "";
for (char ch: text) {
str += huffmanCode[ch];
}
cout << "nEncoded string is :n" << str << 'n';
// traverse the Huffman Tree again and this time
// decode the encoded string
int index = -1;
cout << "nDecoded string is: n";
while (index < (int)str.size() - 2) {
decode(root, index, str);
}
}
// Huffman coding algorithm
int main()
{
string text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);
return 0;
}
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
// A Tree node
class Node
{
char ch;
int freq;
Node left = null, right = null;
Node(char ch, int freq)
{
this.ch = ch;
this.freq = freq;
}
public Node(char ch, int freq, Node left, Node right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
};
class Huffman
{
// traverse the Huffman Tree and store Huffman Codes
// in a map.
public static void encode(Node root, String str,
Map<Character, String> huffmanCode)
{
if (root == null)
return;
// found a leaf node
if (root.left == null && root.right == null) {
huffmanCode.put(root.ch, str);
}
encode(root.left, str + "0", huffmanCode);
encode(root.right, str + "1", huffmanCode);
}
// traverse the Huffman Tree and decode the encoded string
public static int decode(Node root, int index, StringBuilder sb)
{
if (root == null)
return index;
// found a leaf node
if (root.left == null && root.right == null)
{
System.out.print(root.ch);
return index;
}
index++;
if (sb.charAt(index) == '0')
index = decode(root.left, index, sb);
else
index = decode(root.right, index, sb);
return index;
}
// Builds Huffman Tree and huffmanCode and decode given input text
public static void buildHuffmanTree(String text)
{
// count frequency of appearance of each character
// and store it in a map
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0 ; i < text.length(); i++) {
if (!freq.containsKey(text.charAt(i))) {
freq.put(text.charAt(i), 0);
}
freq.put(text.charAt(i), freq.get(text.charAt(i)) + 1);
}
// Create a priority queue to store live nodes of Huffman tree
// Notice that highest priority item has lowest frequency
PriorityQueue<Node> pq = new PriorityQueue<>(
(l, r) -> l.freq - r.freq);
// Create a leaf node for each character and add it
// to the priority queue.
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
pq.add(new Node(entry.getKey(), entry.getValue()));
}
// do till there is more than one node in the queue
while (pq.size() != 1)
{
// Remove the two nodes of highest priority
// (lowest frequency) from the queue
Node left = pq.poll();
Node right = pq.poll();
// Create a new internal node with these two nodes as children
// and with frequency equal to the sum of the two nodes
// frequencies. Add the new node to the priority queue.
int sum = left.freq + right.freq;
pq.add(new Node('', sum, left, right));
}
// root stores pointer to root of Huffman Tree
Node root = pq.peek();
// traverse the Huffman tree and store the Huffman codes in a map
Map<Character, String> huffmanCode = new HashMap<>();
encode(root, "", huffmanCode);
// print the Huffman codes
System.out.println("Huffman Codes are :n");
for (Map.Entry<Character, String> entry : huffmanCode.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("nOriginal string was :n" + text);
// print encoded string
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < text.length(); i++) {
sb.append(huffmanCode.get(text.charAt(i)));
}
System.out.println("nEncoded string is :n" + sb);
// traverse the Huffman Tree again and this time
// decode the encoded string
int index = -1;
System.out.println("nDecoded string is: n");
while (index < sb.length() - 2) {
index = decode(root, index, sb);
}
}
public static void main(String[] args)
{
String text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);
}
}
Nutate bè: a memoria utilizata da a stringa di input hè 47 * 8 = 376 bits è a stringa codificata hè solu 194 bit i.e. data hè cumpressa da circa 48%. In u prugramma C ++ sopra, usemu a classa di stringa per almacenà a stringa codificata per rende u prugramma leggibile.
Perchè e strutture di dati di fila di priorità efficienti necessitanu per inserimentu O(log(N)) tempu, ma in un arbre binariu cumpletu cù N foglie prisenti 2N-1 nodi, è l'arburu Huffman hè un arbulu binariu cumpletu, allora l'algoritmu corre O(Nlog(N)) tempu, induve N - Caratteri.
Sources:
Source: www.habr.com