给定任意一个字符串,给出哈弗曼编码
#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
#include <string.h>
#include <string>
using namespace std;
typedef string huff_type;
struct huff_node
{
huff_node *left,*right;
int wight;
huff_type data;
};
map<huff_type,int> map_w;
/**
* 统计每个单词的频率
*/
map<huff_type ,int> count_fre(char * str)
{
char buf[2];
buf[1] = 0;
size_t len = strlen(str);
map<huff_type ,int> map_fre;
map_fre.clear();
for(int i=0 ; i<len ; i++)
{
buf[0] = str[i];
huff_type ch = buf;
if(map_fre.find(ch) != map_fre.end())
{
map_fre[ch] = map_fre[ch] + 1;
}
else
{
map_fre[ch] = 1;
}
}
//
// map<huff_type ,int>::iterator it;
// for(it=map_fre.begin();it!=map_fre.end();++it)
// cout<<"key: "<<it->first <<" value: "<<it->second<<endl;
return map_fre;
}
huff_node * create_huffman(map<huff_type ,int> map_fre)
{
huff_node **b = new huff_node*[map_fre.size()];
map<huff_type ,int>::iterator it;
int i;
for(it=map_fre.begin(),i=0;it!=map_fre.end();++it,i++)
{
// cout<<"key: "<<it->first <<" value: "<<it->second<<endl;
b[i] = new huff_node();
b[i]->data = it->first;
b[i]->left = b[i]->right = NULL;
b[i]->wight = it->second;
}
int size = map_fre.size() - 1;
// printf("%d",size);
int first,second;
while(size--)
{
first = second = -1;
for(i=0 ; i<map_fre.size() ; i++)
{
if(b[i] == NULL) continue;
if(first == -1)
first = i;
else if(b[i]->wight < b[first]->wight)
{
second = first;
first = i;
}
else if(second == -1 || b[i]->wight < b[second]->wight)
second = i;
}
// cout << "delete first key " << b[first]->data << " value: " << b[first]->wight << endl;
// cout << "delete second key " << b[second]->data << " value: " << b[second]->wight << endl;
huff_node *node = new huff_node();
node->data = b[first]->data + b[second]->data;
node->wight = b[first]->wight + b[second]->wight;
node->left = b[first];
node->right = b[second];
b[first] = node;
b[second] = NULL;
}
return b[first];
}
map<huff_type,string> huff_code;
void get_huffcode(huff_node *node , string now)
{
if(node==NULL)
return ;
else
{
if(node->left == NULL && node->right==NULL)
{
huff_code[node->data] = now;
//每个字符的huffman编码
// cout << "key " << node->data << " is " << now << endl;
}
else
{
get_huffcode(node->left, now+"0");
get_huffcode(node->right, now+"1");
}
}
}
int main()
{
// map_w.clear();
// char str[255] = "abcdabcaba";
char str[255] ;
gets(str);
map_w = count_fre(str);
huff_node *head = NULL;
head = create_huffman(map_w);
get_huffcode(head, "");
char buf[2];
buf[1] = 0;
for(int i=0 ; i< strlen(str) ; i++)
{
buf[0] = str[i];
cout<<huff_code[buf];
}
cout<<endl;
return 0;
}