-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHUFFMAN CODING.cpp
More file actions
154 lines (110 loc) · 2.87 KB
/
HUFFMAN CODING.cpp
File metadata and controls
154 lines (110 loc) · 2.87 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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include<bits/stdc++.h>
using namespace std;
struct node
{
node * leftChild;
node * rightChild;
double frequency;
string content;
string code;
};
vector<node> nodeArray;// Use nodeArray to record all the nodes that may be created in the whole process
node extractMin()
{
double temp = (double) INT_MAX;
vector<node>::iterator i1,pos;
for(i1 = nodeArray.begin(); i1!=nodeArray.end(); i1++)
{
if(temp>(*i1).frequency)
{
pos = i1;
temp = (*i1).frequency;
}
}
node tempNode = (*pos);
nodeArray.erase(pos);
return tempNode;
}
node getHuffmanTree()
{
while(!nodeArray.empty())
{
node * tempNode = new node;
node * tempNode1 = new node;
node * tempNode2 = new node;
*tempNode1 = extractMin();
*tempNode2 = extractMin();
tempNode->leftChild = tempNode1;
tempNode->rightChild = tempNode2;
tempNode->frequency = tempNode1->frequency+tempNode2->frequency;
nodeArray.push_back(*tempNode);
if(nodeArray.size() == 1)//only the root node exsits
{
break;
}
}
return nodeArray[0];
}
void BFS(node * temproot,string s)
{
node * root1 = new node;
root1 = temproot;
root1->code = s;
if(root1 == NULL)
{
}
else if(root1->leftChild == NULL && root1->rightChild == NULL)
{
cout<<"the content is "<<root1->content<<endl;
cout<<"and its corresponding code is "<<root1->code<<endl;
}
else
{
root1->leftChild->code = s.append("0");
s.erase(s.end()-1);
root1->rightChild->code = s.append("1");
s.erase(s.end()-1);
BFS(root1->leftChild,s.append("0"));
s.erase(s.end()-1);
BFS(root1->rightChild,s.append("1"));
s.erase(s.end()-1);
}
}
void getHuffmanCode()
{
int size,i;
double tempDouble;
string tempString = "";
cout<<"please input the number of things you want to encode!"<<endl;
cin>>size;
for(i = 0; i<size; i++)
{
cout<<"please input the things you want to encoded and their frequencies!"<<endl;
node tempNode;
cin>>tempString;
cin>>tempDouble;
tempNode.frequency = tempDouble;
tempNode.content = tempString;
tempNode.leftChild = NULL;
tempNode.rightChild = NULL;
nodeArray.push_back(tempNode);
}
node root = getHuffmanTree();
BFS(&root,"");
}
int main()
{
int n;
vector<int> test;
cin>>n;
for(int i=0; i<n; i++)
{
int a;
cin>>a;
test.push_back(a);
}
vector<int>::iterator i1 = test.begin();
test.erase(i1);
getHuffmanCode();
return 0;
}