forked from prashantkalokhe/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
huffman.cpp
111 lines (81 loc) · 1.62 KB
/
huffman.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
100
101
102
103
104
105
106
107
108
109
110
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int freq;
char ch;
Node* left,*right;
Node(int f, char c, Node* l=NULL, Node* r=NULL)
{
freq=f;
ch=c;
left=l;
right=r;
}
};
struct compare
{
bool operator()(Node* l , Node* r)
{
return l->freq > r->freq;
}
};
void printCodes(Node* root, string str="")
{
if(root->ch != '$')
{
cout<<root->ch<<" "<<str<<"\n";
return;
}
printCodes(root->left, str+"0");
printCodes(root->right, str+"1");
}
void printHCodes(char arr[], int freq[], int n)
{
priority_queue<Node*, vector<Node*> , compare> h;
for(int i=0; i<n;i++)
{
h.push(new Node(freq[i],arr[i]));
}
while( h.size() > 1)
{
Node* l = h.top();
h.pop();
Node* r = h.top();
h.pop();
Node* node = new Node(l->freq+r->freq,'$',l,r);
h.push(node);
}
printCodes(h.top());
}
/*struct compare
{
bool operator()(Node* l , Node* r)
{
return l->freq > r->freq;
}
};*/
int main()
{
int n;
cout<<"Enter the number of distinguished characters : "<<endl;
cin>>n;
char arr[n];
int freq[n];
for(int i=0;i<n;i++)
{
cout<<"Character "<<(i+1)<<" : ";
cin>>arr[i];
cout<<"Frequncy "<<(i+1)<<" : ";
cin>>freq[i];
}
cout<<"CHARACTERS AND THEIR FREQUENCIES : "<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<"\t"<<freq[i]<<endl;
}
cout<<"Characters and their codes : "<<endl;
printHCodes(arr, freq, n);
return 0;
}