-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathHuffman_Coding.cpp
More file actions
98 lines (78 loc) · 1.63 KB
/
Huffman_Coding.cpp
File metadata and controls
98 lines (78 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// ---------------- OUTPUT -----------------------
// Enter the number of elements
// 5
// Enter the characters
// A B C D F
// Enter the frequencies of characters
// 5 1 2 4 10
// Huffman Codes are :
// F : 0
// A : 10
// B : 1100
// C : 1101
// D : 111
// ------------------------------------------------
#include <bits/stdc++.h>
using namespace std;
struct Node {
char data;
int freq;
Node *left, *right;
Node(char data, int freq)
{
left = right = NULL;
this->data = data;
this->freq = freq;
}
};
struct compare{
bool operator()(Node* l, Node* r)
{
return (l->freq > r->freq);
}
};
void print(struct Node* root, string str)
{
if (!root)
return;
if (root->data != '$')
cout <<root->data<<" : "<<str<<"\n";
print(root->left,str+"0");
print(root->right,str+"1");
}
void HuffmanCoding(char data[], int freq[], int n)
{
Node *left, *right, *top;
priority_queue<Node*, vector<Node*>, compare> minHeap;
for (int i = 0; i < n; ++i)
minHeap.push(new Node(data[i], freq[i]));
while (minHeap.size() != 1) {
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
top = new Node('$', left->freq + right->freq);
top->left = left;
top->right = right;
minHeap.push(top);
}
cout<<endl;
cout<<"Huffman Codes are : "<<endl;
print(minHeap.top(), "");
}
int main()
{
cout<<"Enter the number of elements"<<endl;
int n;
cin>>n;
cout<<"Enter the characters"<<endl;
char arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<"Enter the frequencies of characters"<<endl;
int freq[n];
for(int i=0;i<n;i++)
cin>>freq[i];
HuffmanCoding(arr, freq, n);
return 0;
}