-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ba8e942
commit 53a557b
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
#include<iostream> | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
struct MinHeapNode | ||
{ | ||
char number; | ||
unsigned freq; | ||
MinHeapNode *left, *right; | ||
MinHeapNode(char number, unsigned freq) | ||
{ | ||
left = right = NULL; | ||
this->number = number; | ||
this->freq = freq; | ||
} | ||
}; | ||
struct compare { | ||
bool operator()(MinHeapNode* l, MinHeapNode* r) | ||
{ | ||
return (l->freq > r->freq); | ||
} | ||
}; | ||
void printCodes(struct MinHeapNode* root, string code) | ||
{ | ||
|
||
if (!root) | ||
return; | ||
|
||
if (root->number != '$') | ||
cout << root->number<< ": "<<code<<"\n"; | ||
|
||
printCodes(root->left,code+"0"); | ||
printCodes(root->right,code+"1"); | ||
} | ||
void Huffman(char number[], int freq[], int size) | ||
{ | ||
struct MinHeapNode *left, *right, *top; | ||
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap; | ||
|
||
for (int i = 0; i < size; ++i) | ||
minHeap.push(new MinHeapNode(number[i], freq[i])); | ||
while (minHeap.size() != 1) | ||
{ | ||
left = minHeap.top(); | ||
minHeap.pop(); | ||
|
||
right = minHeap.top(); | ||
minHeap.pop(); | ||
top = new MinHeapNode('$', left->freq + right->freq); | ||
|
||
top->left = left; | ||
top->right = right; | ||
|
||
minHeap.push(top); | ||
} | ||
printCodes(minHeap.top(), ""); | ||
} | ||
|
||
int main() | ||
{ | ||
|
||
char img[] = {'0','1','2','3','4','5','6','7'}; | ||
int freq[] = {1,4,2,3,2,12,10,2}; | ||
|
||
int size = sizeof(img) / sizeof(img[0]); | ||
|
||
Huffman(img, freq, size); | ||
|
||
return 0; | ||
} |