File tree Expand file tree Collapse file tree 1 file changed +83
-0
lines changed
Greedy Algorithms/Huffman_Encoding Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ // leaf node contains character(data), intermediate nodes contains frequency
5
+ struct node
6
+ {
7
+ struct node *l;
8
+ struct node *r;
9
+ char data;
10
+ int freq;
11
+ };
12
+
13
+ struct compare {
14
+ bool operator ()(struct node *n1,struct node *n2)
15
+ {
16
+ return n1->freq >n2->freq ;
17
+ }
18
+ };
19
+
20
+ void traverse (node *root,string str)
21
+ {
22
+ if (!root)
23
+ return ;
24
+
25
+ if (root->data !=' #' ){
26
+ cout<<str<<" " ;
27
+ return ;}
28
+
29
+ // append 0 if traverse to left branch of the node otherwise append 1
30
+
31
+ // if(root->l)
32
+ traverse (root->l ,str+" 0" );
33
+ // if(root->r)
34
+ traverse (root->r ,str+" 1" );
35
+ }
36
+ int main () {
37
+ // code
38
+
39
+ int t; // for number of test cases
40
+ cin>>t;
41
+ while (t--)
42
+ {
43
+ string s;
44
+ cin>>s;
45
+ priority_queue<node*,vector<node*>,compare> pq;// minheap;
46
+
47
+
48
+ int x;
49
+ for (int i=0 ;i<s.length ();i++)
50
+ {
51
+ struct node *nn=(struct node *)malloc (sizeof (struct node ));
52
+ cin>>x;
53
+ nn->freq =x;
54
+ nn->data =s[i];
55
+ nn->l =nn->r =NULL ;
56
+ pq.push (nn);
57
+ }
58
+
59
+ while (pq.size ()!=1 )
60
+ {
61
+ struct node *left=pq.top ();
62
+ pq.pop ();
63
+
64
+ struct node *right=pq.top ();
65
+ pq.pop ();
66
+
67
+ node *heapNode=(node*)malloc (sizeof (node));
68
+ heapNode->data =' #' ; // '#'' acts as character in intermediate nodes
69
+ heapNode->freq =left->freq +right->freq ;
70
+ heapNode->l =left;
71
+ heapNode->r =right;
72
+
73
+ pq.push (heapNode);
74
+ }
75
+
76
+ struct node *root=pq.top ();
77
+ string ans=" " ;
78
+ traverse (root,ans);
79
+ cout<<endl;
80
+
81
+ }
82
+ return 0 ;
83
+ }
You can’t perform that action at this time.
0 commit comments