-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffmanncodeing.c++
More file actions
84 lines (84 loc) · 1.82 KB
/
huffmanncodeing.c++
File metadata and controls
84 lines (84 loc) · 1.82 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
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
class cmp
{
public:
bool operator()(Node *a, Node *b)
{
return a->data > b->data;
}
};
class solution
{
public:
void traverse(Node* root,vector<string>& ans, string temp)
{
if(root->left==NULL && root->right==NULL)
{
ans.push_back(temp);
return;
}
traverse(root->left,ans,temp+'0');
traverse(root->right,ans,temp+'1');
}
vector<string> huffcode(string s, vector<int> f, int n)
{
priority_queue<Node *, vector<Node *>, cmp> minheap;
for (int i = 0; i < n; i++)
{
Node *newnode = new Node(f[i]);
minheap.push(newnode);
}
while(minheap.size()>1)
{
Node* first=minheap.top();
minheap.pop();
Node* second=minheap.top();
minheap.pop();
Node* newnode=new Node(first->data+second->data);
newnode->left=first;
newnode->right=second;
minheap.push(newnode);
}
Node* root=minheap.top();
minheap.pop();
vector<string> ans;
string temp="";
traverse(root,ans,temp);
return ans;
}
};
int main()
{
string s;
cout << "Enter the string: " << endl;
cin >> s;
cout << "Enter The frequency: " << endl;
vector<int> f(s.length(),0);
for (int i = 0; i < s.length(); i++)
{
cin >> f[i];
}
solution ans;
vector<string>ans1=ans.huffcode(s,f,s.length());
for(int i=0;i<ans1.size();i++)
{
cout<<s[i]<<" "<<ans1[i]<<endl;
}
}