forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuffman.cpp
100 lines (82 loc) · 1.79 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
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct node{
char value;
float freq;
node* right;
node* left;
};
struct compare{
bool operator()(const node &n1, const node &n2) const{
return n1.freq>n2.freq;
}
};
//IS CORRECT
node * mergeNodes(node *n1, node *n2){
node *n=new node;
n->freq=n1->freq+n2->freq;
n->right=n2;
n->left=n1;
n->value='~';
return n;
}
void printArr(int arr[], int n){
for(int i=0; i<n; i++){
printf("%d", arr[i]);
}
cout<<endl;
}
void codes(node *root, int arr[], int top){
if(root->left!=NULL){
arr[top]=0;
codes(root->left, arr, top+1);
}
if(root->right!=NULL){
arr[top]=1;
codes(root->right, arr, top+1);
}
if(root->left==NULL && root->left==NULL){
cout<<root->value<<"\t : ";
printArr(arr, top);
}
}
int main(){
string s;
cout<<"Enter String: ";
cin>>s;
int n=s.length();
priority_queue<node, vector<node>, compare> pq;
for(int i=0; i<n; i++){
float count=1;
if(s[i]!='~'){
for(int j=i+1; j<n; j++){
if(s[i]==s[j]){
count++;
s[j]='~';
}
}
node nd;
nd.value=s[i];
nd.left=NULL;
nd.right=NULL;
nd.freq= (count/float(n));
pq.push(nd);
}
}
node *n1, *n2;
node *root;
while(pq.size()>1){
n1=new node;
n2=new node;
*n1=pq.top();
pq.pop();
*n2=pq.top();
pq.pop();
root=mergeNodes(n1,n2);
pq.push(*root);
}
int *arr=new int[100];
codes(root, arr, 0);
return 0;
}