-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huffman_coding_Data_Compression.cpp
99 lines (65 loc) · 1.54 KB
/
Huffman_coding_Data_Compression.cpp
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
99
//g++ 5.4.0
#include <bits/stdc++.h>
using namespace std;
struct node{
int frequency;
char in;
node * left;
node * right;
node(int freq, char i)
{
frequency=freq;
in = i;
left=NULL;
right=NULL;
}
};
struct comparator{
bool operator()(node*one,node*two)
{
if(one->frequency>two->frequency)return true;
else return false;
}
};
void obtain_huffmancodes(node*rootm, string current)
{
if(rootm->left== NULL && rootm->right== NULL && rootm->in!='0')
{
cout<<rootm->in<<"-"<<current<<endl;
return;
}
obtain_huffmancodes(rootm->left, string(current+"0"));
obtain_huffmancodes(rootm->right, string(current+"1"));
}
int main()
{
string input;
cin>>input;
unordered_map<char,int> freq;
for(int i=0;i<input.size();i++)
{
freq[input[i]]++;
}
priority_queue<node*, vector<node*>, comparator> container;
for(auto val:freq)
{
node* temp=new node(val.second, val.first);
container.push(temp);
}
//cout<<container.top()->in<<endl;
while(container.size()>=2)
{
node*one=container.top();
container.pop();
node * two = container.top();
container.pop();
node* curr=new node(one->frequency+two->frequency,'0');
curr->left = one;
curr->right= two;
container.push(curr);
}
node*rootm = container.top();
container.pop();
string ans="";
obtain_huffmancodes(rootm,ans);
}